每次用户打开我的应用程序时,我都会将用户名和时间戳保存到文本文件中。我希望能够打开文本文件,如果用户名已经存在,请将用户名/时间戳替换为当前用户名/时间戳。如果是这样,可能会显示该人也打开了多少次。这是我保存到我的文本文件:
Dim DomainInfo As Object
Dim Username As String
DomainInfo = CreateObject("WScript.Network")
Username = DomainInfo.Username
Dim path As String = "C:\myfolder"
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
Else
Dim filename As String = "C:\myfolder\user.log"
Dim sw As StreamWriter = AppendText(filename)
sw.WriteLine(Now() & " " & Username)
sw.Close()
File.SetAttributes(filename, FileAttributes.Hidden)
End If
答案 0 :(得分:0)
您可以从文本文件中读取您的程序并更改所需的文本并将其全部写回文本文件中
Dim lstTextFile As List(Of String) = System.IO.File.ReadAllLines(filename).ToList
For each line In lstTextFile
'edit your line here if meets requirements, an if statement would probably work
Next
'the below line writes it back to the file
System.IO.File.WriteAllLines(filename, lstTextFile.ToArray, System.Text.Encoding.Default)
使用您的代码更新了示例:
Dim filename As String = "C:\myfolder\user.log"
Dim lstTextFile As List(Of String) = System.IO.File.ReadAllLines(filename).ToList
For each line In lstTextFile
If line.contains(username) then
lstTextFile.remove(line)
End If
Next
lstTextFile.add(Now() & " " & Username)
System.IO.File.WriteAllLines(filename, lstTextFile.ToArray, System.Text.Encoding.Default)
答案 1 :(得分:0)
如果你想删除它们:
Dim Username = Environment.Username
Dim filename = "C:\myfolder\user.log"
Dim linesremoved = 0
If File.Exists(filename) Then
Dim lines = File.ReadAllLines(filename)
Dim lookup = lines.ToLookup(Function(l) l.EndsWith(Username))
linesremoved = lookup(True).Count ' the number of lines that end with the Username
If linesremoved > 0 Then File.WriteAllLines(filename, lookup(False).ToArray)
End If