在特定文本后阅读 Txt 上的行 VB.NET

Read line on Txt after specific text VB.NET

我的记事本上有以下文字:

Manufacture, a, b, c
Manufacture, h, i, j
Supplier, 7, 8, 9
Manufacture, x, y, z
Supplier, 0,9,5

然后我有一个包含 2 个文本框的表单。 1 用于制造,2 用于供应商。
我怎样才能拆分它?所以当我按下 read 按钮时。文本框将是:

文本框制造商

Manufacture, a, b, c
Manufacture, h, i, j
Manufacture, x, y, z

文本框供应商

Supplier, 7,8,9
Supplier, 0,9,5

目前,我有以下代码。但还是很基础。

Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

此版本将读取您的输入文件、确定行 ID 并构建值数组。 最后使用新行加入值并分配到文本框中。

   Private Sub ParseInputFile(filePath As String)

        Dim lines() As String = File.ReadAllLines(filePath)

        Dim manufs As New List(Of String)
        Dim suppliers As New List(Of String)

        For Each lineItem As String In lines

            Dim vals() As String = lineItem.Split(Convert.ToChar(","))

            If vals.Length > 0 Then

                Dim lineId As String = vals(0)
                If lineId = "Manufacture" Then
                    manufs.Add(lineItem)
                ElseIf lineId = "Supplier" Then
                    suppliers.Add(lineItem)
                End If

            End If

        Next

        TextboxManufacture.Text = String.Join(Environment.NewLine, manufs)
        TextboxSupplier.Text = String.Join(Environment.NewLine, suppliers)

    End Sub

我读了你的问题,因为它对我来说很有趣,而且我知道获得结果的不同方法,请随时检查代码并享受你将获得的结果。

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim oReader As System.IO.StreamReader = Nothing
    Dim str1 As String = ""
    Try
        oReader = New IO.StreamReader(".\data.txt") 'path with the file with the data to be read.
        str1 = oReader.ReadLine 'try to read the first line of the file data.txt
    Catch ex As Exception
        oReader.Close() 'important: in case of error don't forget close the oReader for free the pointer to data.txt.
    End Try
    While Not str1 Is Nothing
        Dim pos As Byte = str1.IndexOf(",") 'first occurence of character comma, from left to right.
        Dim str2 As String = str1.Substring(0, pos) 'string with the first part of the string, (Manufacture, Supplier).
        Dim str3 As String = str1.Substring(pos + 2, str1.Length - 2 - pos) 'string with the second part of the string.
        Select Case str2
            Case "Manufacture"
                TextboxManufacture.Text &= str3 & vbCrLf 'we add to TextboxManufacture the data and a newline character
            Case "Supplier"
                TextboxSupplier.Text &= str3 & vbCrLf 'we add to TextboxSupplier the data and a newline character
        End Select
        str1 = oReader.ReadLine 'read a new line of the file data.txt
    End While
    oReader.Close() 'important: when finished of read lines, it free the pointer to data.txt
End Sub
End Class