繁体   English   中英

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

[英]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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM