vb.net 如何获取包含字符串的整行文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15030827/
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
How to get the whole line of text that contain a string
提问by Fariz Luqman
There's one thing that I want to ask. How can I get the whole line of text that contain a string in Visual Basic 2010?
我想问一件事。如何在 Visual Basic 2010 中获取包含字符串的整行文本?
Let's say:
让我们说:
MyText.txt file contains:
MyText.txt 文件包含:
Configurations:
Name: Fariz Luqman
Age: 78
My Favourite Fruit: Lemon, Apple, Banana
My IPv4 Address: 10.6.0.5
My Car: Ferrari
In Visual Basic, I want to get the whole line of text that contain the string "Banana" and print it in the textbox so it will display in that textbox:
在 Visual Basic 中,我想获取包含字符串“ Banana”的整行文本并将其打印在文本框中,以便在该文本框中显示:
My Favourite Fruit: Lemon, Apple, Banana
Why am I doing this? Because the text file is being appended and the line number is random. The contents is also random because the texts is generated by Visual Basic. The text "Banana" can be in line 1, line 2 or can be in any line so how can I get the whole line of text that contain certain string?
我为什么要这样做?因为文本文件正在被追加并且行号是随机的。内容也是随机的,因为文本是由 Visual Basic 生成的。文本“Banana”可以在第 1 行、第 2 行或任何行中,那么如何获取包含特定字符串的整行文本?
Thank you in advance!
先感谢您!
回答by Steven Doggart
You can do this easily all in one line with LINQ:
您可以使用 LINQ 在一行中轻松完成此操作:
TextBox1.Text = File.ReadAllLines("MyText.txt").FirstOrDefault(Function(x) x.Contains("Banana"))
However, if the file is rather large, that's not particularly efficient, since it will read the whole file into memory before searching for the line. If you want to make it stop loading the file once it finds the line, could use the StreamReader, like this:
但是,如果文件相当大,那不是特别有效,因为它会在搜索行之前将整个文件读入内存。如果您想让它在找到该行后停止加载文件,可以使用StreamReader,如下所示:
Using reader As New StreamReader("Test.txt")
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains("Banana") Then
TextBox1.Text = line
Exit While
End If
End While
End Using
回答by Melanie
Just checked (should have done that first!). VB.Net does have a CONTAINS() method. So:
刚刚检查(应该先这样做!)。VB.Net 确实有一个 CONTAINS() 方法。所以:
IF line1.Contains("Banana") THEN
'do something
END IF

