循环遍历 VB.NET 中的文本文件的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25731772/
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
Loop through the lines of a text file in VB.NET
提问by OmnivorousOctopus
I have a text file with some lines of text in it.
我有一个文本文件,其中包含一些文本行。
I want to loop through each line until an item that I want is found*, then display it on the screen, in the form of a label.
我想遍历每一行,直到找到我想要的项目*,然后以标签的形式将其显示在屏幕上。
*I am searching for the item through a textbox.
*我正在通过文本框搜索该项目。
That is, in sudo:
也就是说,在 sudo 中:
For i = 0 To number of lines in text file
If txtsearch.text = row(i).text Then
lbl1.text = row(i).text
Next i
回答by Eminem
You can use the File.ReadLines Methodin order to iterate throughout your file, one line at a time. Here is a simple example:
您可以使用File.ReadLines 方法来遍历整个文件,一次一行。这是一个简单的例子:
Dim Term As String = "Your term"
For Each Line As String In File.ReadLines("Your file path")
If Line.Contains(Term) = True Then
' Do something...Print the line
Exit For
End If
Next
回答by ???ěxě?
Here's a function that will spit back your string from the row that contains your search term...
这是一个函数,它将从包含您的搜索词的行中吐出您的字符串......
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
To use the function you can do this...
要使用该功能,您可以这样做...
Dim strText As String = SearchFile(FileName, SearchTerm)
If strText <> String.Empty Then
Label1.Text = strText
End If
回答by DEEPU
LOOPING AND GETTING ALL XML FILES FROM DIRECTORY IF WE WANT TEXTFILES PUT "*.txt" IN THE PLACE OF "*xml"
如果我们希望文本文件将“*.txt”放在“*xml”的位置,则循环并从目录中获取所有 XML 文件
Dim Directory As New IO.DirectoryInfo(Path)
Dim 目录作为新 IO.DirectoryInfo(Path)
Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.xml")
allFiles = allFiles.OrderByDescending(Function(x) x.FullName).ToArray()
Dim singleFile As IO.FileInfo
For Each singleFile In allFiles
'ds.ReadXml(singleFile)
xd.Load(singleFile.FullName)
Dim nodes As XmlNodeList = xd.DocumentElement.SelectNodes("/ORDER/ORDER_HEADER")
Dim ORDER_NO As String = " "
For Each node As XmlNode In nodes
If Not node.SelectSingleNode("ORDER_NO") Is Nothing Then
ORDER_NO = node.SelectSingleNode("ORDER_NO").InnerText
End If
Next
Next