Web.11
Web.11

Reputation: 416

Remove a line from text file vb.net

I'm using vb.net windows form app. I want to remove line from list of lines.

So if the line in textbox exists on that list, to be remove from list, and file to be saved.

I have a file list.txt with list of numbers :

123-123
321-231
312-132

If I write in textbox : 321-231 and if list.txt contains that line then remove it. so result need to be :

123-123
321-132

I was trying with this code :

 Dim lines() As String
  Dim outputlines As New List(Of String)
        Dim searchString As String = Textbox1.Text
         lines = IO.File.ReadAllLines("D:\list.txt")
         For Each line As String In lines
             If line.Contains(searchString) = True Then
                 line = ""  'Remove that line and save text file (here is my problem I think )
                 Exit For
             End If
         Next

Upvotes: 2

Views: 16711

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34846

Put each string as you process it in the outputlines list, unless it matches the value typed in, like this:

Dim lines() As String
Dim outputlines As New List(Of String)
Dim searchString As String = Textbox1.Text
lines = IO.File.ReadAllLines("D:\list.txt")

For Each line As String In lines
    If line.Contains(searchString) = False Then
        outputlines.Add(line)
    End If
Next

Now outputlines matches every line that did not match what was typed in by the user and you can write the contents of the outputlines list to file.

Upvotes: 4

Related Questions