簡體   English   中英

在VB.NET中循環遍歷文本文件的行

[英]Loop through the lines of a text file in VB.NET

我有一個文本文件,其中包含一些文本行。

我想遍歷每一行,直到找到我想要的項目*,然后以標簽的形式將其顯示在屏幕上。

*我正在通過文本框搜索該項目。

也就是說,在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

您可以使用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

這是一個函數,它會從包含搜索詞的行中吐出你的字符串......

  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

要使用此功能,您可以執行此操作...

 Dim strText As String = SearchFile(FileName, SearchTerm)
 If strText <> String.Empty Then
   Label1.Text = strText
 End If

如果我們想要TEXTFILES將“* .txt”放在“* xml”的位置,則從目錄中循環並獲取所有XML文件

Dim目錄為新的IO.DirectoryInfo(路徑)

    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM