文件结构
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
答案 0 :(得分:4)
您需要一个数据结构,您可以在其中加载行,然后启动循环
' 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"的一行内容应始终跟随三行数据。 (三条数据线之间不允许有空行)
答案 1 :(得分:-1)
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