Help Man Help Man - 4 months ago 8
Vb.net Question

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

Answer

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) 
Comments