Home > Enterprise >  Deleting all lines in text file until you get to a word vb.net
Deleting all lines in text file until you get to a word vb.net

Time:07-19

Very new to vb.net, apologies if this is basic. I am trying to open up a text file and delete all the lines starting at index 0 until I hit the line that has the word I am looking for. Right now, it just deletes the word I put in it.

        ' Read the file line by line
        Using reader As New IO.StreamReader(fileName)
            While Not reader.EndOfStream()
                Dim input As String = reader.ReadLine()

                'Delete all lines up to String
                Dim i As Integer
                i = 0
                For i = 0 To input.Contains("{MyWord}")
                    builder.AppendLine(input)
                Next

            End While
        End Using

CodePudding user response:

I would tend to do it like this:

Dim lines = File.ReadLines(filePath).
                 SkipWhile(Function(line) Not line.Contains(word)).
                 ToArray()

File.WriteAllLines(filePath, lines)

The File.ReadLines method reads the lines of the file one by one and exposes them for processing as they are read. That's in contrast to the File.ReadAllLines method, which reads all the lines of the file and returns them in an array, at which case you can do as desired with that array.

The SkipWhile method will skip the items in a list while the specified condition is True and expose the rest of the list, so that code will skip lines while they don't contain the specified word and return the rest, which are then pushed into an array and returned. That array is then written back over the original file.

Just note that String.Contains is case-sensitive. If you're using .NET Core 2.1 or later then there is a case-insensitive overload but older versions would require the use of String.IndexOf for case-insensitivity.

CodePudding user response:

Partial. You didn't say what to do with the rest of the lines...

Did you mean lines?

    Dim ShouldRead as Boolean
    Dim builder As New System.Text.StringBuilder
    Using reader As New IO.StreamReader(fileName)
        'Delete all lines without String
        While Not reader.EndOfStream()
            Dim input As String = reader.ReadLine()
            If input.Contains("{MyWord}") Then ShouldRead = True
            If ShouldRead Then
                builder.AppendLine(input)                    
            End If
        End While
    End Using
  • Related