Remove a line from text file vb.net

北城余情 提交于 2019-12-13 15:23:00

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/20222681/remove-a-line-from-text-file-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!