从文本文件 vb.net 中删除一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20222681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove a line from text file vb.net
提问by Web.11
I'm using vb.net windows form app. I want to remove line from list of lines.
我正在使用 vb.net windows 窗体应用程序。我想从行列表中删除行。
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 :
我有一个包含数字列表的文件 list.txt:
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 :
如果我在文本框中写入: 321-231 并且如果 list.txt 包含该行,则将其删除。所以结果必须是:
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
回答by Karl Anderson
Put each string as you process it in the outputlineslist, unless it matches the value typed in, like this:
将处理时的每个字符串放入outputlines列表中,除非它与输入的值匹配,如下所示:
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 outputlinesmatches every line that did not match what was typed in by the user and you can write the contents of the outputlineslist to file.
现在outputlines匹配与用户输入的内容不匹配的每一行,您可以将outputlines列表的内容写入文件。

