繁体   English   中英

使用Vb.net读取复杂的文本文件

[英]Read complex text file using Vb.net

档案结构

RECORD
1234567890,123456789,1234567,Address1,,City,State,Zip,USA,Phone,,,,,,,,,
EmpName,DBAName,ID,,Address1,,Address1,City,60603,USA,234567890,,,,
C,03/13/2017,,1,2,
RECORD
1234567890,123456789,1234567,Address1,,City,State,Zip,USA,Phone,,,,,,,,,
EmpName2,DBAName2,ID2,,Address2,,Address2,City2,60603,USA,234567890,,,,
C,03/13/2017,,1,2,

看上面的文件结构,我想遍历文件,对于每个记录(RECORD),我想将下三行放在一个数组中,然后将下一个记录放在单独的数组中。

我正在寻找框架代码,我在使用流阅读器进行编程方面是一个新手。

到目前为止的代码

 Dim read As New System.IO.StreamReader("C:\New Text.txt")
       Dim a As String

       For Each a In read.ReadLine
           If read.ReadLine.Equals("RECORD") Then
               \\How do I read next 3 lines and put them in one array with comma delimiter
           End If
       Next

您需要一个数据结构,在该结构中将保持行的加载,然后开始循环

' Here you will keep the 3 lines block joined together and splitted on comma
Dim records = new List(Of String())()

Using read As New System.IO.StreamReader("C:\New Text.txt")
   Dim a As String

   ' Read each line (Assuming that we start with a RECORD line
   For Each a In read.ReadLine
       ' Do not read another line, but just test what is present in the string
       If a.Equals("RECORD") Then

          ' Now read the 3 following lines....
          Dim line1 = read.ReadLine
          Dim line2 = read.ReadLine
          Dim line3 = read.ReadLine
          'Join the lines togeter
          Dim record = string.Join("", line1, line2, line3).
          ' Split on the comma to produce an array of strings. The fields.
          Dim fields = record.Split(","c)
          records.Add(fields)
       End If
   Next
End Using

当然,应该使用适当的类来描述您的输入来增强此效果,其中该类的每个属性都代表加载的CSV文件的字段。 然后您可以将List(Of String())更改为List(Of YourClassData)

请记住,此解决方案非常依赖于确切的文件结构。 具有“ RECORD”内容的一行应始终跟随三行数据。 (三个数据行之间不允许有空行)

     Dim read As New System.IO.StreamReader("C:\New Text.txt")
//I usually only do C#, but rough VB.NEt code: I did not rcreate your array for you, figured you got that :-)
       Dim a As String
       Dim myConcatString as String
       For Each a In read.ReadLine
          Dim myReadLine as String 
            myReadLine = read.ReadLine
           If myReadLine.Equals("RECORD") Then
myConcatString = myConcatString  & myReadLine 
               \\How do I read next 3 lines and put them in one array with comma delimiter
           else
           //add myConcatString to array if not null....
myConcatString =""
           End If
       Next

暂无
暂无

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

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