Search code examples
.netvb.nettexttext-files

How to delete a line from a txt after reading it


I need to delete a line from a txt after I read it. To read line by line I use

Dim srdFile As IO.StreamReader

       srdFile = New IO.StreamReader("shazam.txt")
       Do Until srdFile.Peek = -1
           strLine = srdFile.ReadLine()

           ... how to delete the line here..
       ' here i call another function 
       Loop

       srdFile.Close()

How can I delete it the lines after they are being read? Also how can I save the file everytime i delete a line?. Thanks


Solution

  • That's not a good idea. You would have to delete the first line after reading and move all lines to the top afterwards, so basically you had to rewrite the whole file in each line. Thats not what you want. But you could process each line and determine which could not be processed successfuly. Then you can clear the file and write the remaing lines into that file:

    Dim failResults = From line In IO.File.ReadLines(path)
                      Select result = (Line:=line, ProcessResult:=ProcessLine(line))
                      Where result.ProcessResult = False
                      Select result.Line
    Dim remainingLines = failResults.ToList()
    IO.File.WriteAllText(path, "")
    IO.File.WriteAllLines(path, remainingLines)
    

    Here's a method which you have to fill with your logic:

    Private Function ProcessLine(line As String) As Boolean
        ' do something with this line and return if it was successful, so can be deleted
        Return True
    End Function