简体   繁体   中英

Replacing the line of text if username is the same in text file?

I'm saving a username and time stamp into a text file every time a user opens my application. I want to be able to open the text file and if the username already exist, replace the username/timestamp with current one. If so, possibly show how many times that person has also opened it as well. Here's my saving to my text file:

    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

You could read from the text file into your program and change the required text and write it all back into the text file from scratch

 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)

Updated example using your code:

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) 

If you want to remove them:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM