我想知道是否有办法从多个文本文件中读取多行逗号分隔文本并将它们全部存储在同一个数组中而不覆盖已存在的数据?我尝试了很多东西,似乎没有什么工作。所以,例如:
Dim reader As TextFieldParser = New TextFieldParser("text1.txt")
reader.TextFieldType = FieldType.Delimited
reader.SetDelimiters(",")
Dim currentrow as string() = reader.ReadFields()
Dim storageArray() as string()
storageArray(0) = currentrow(0)
storageArray(1) = currentrow(1)
currentrow = reader.ReadFields()
storageArray(2) = currentrow(0)
storageArray(3) = currentrow(1)
Dim reader As TextFieldParser = New TextFieldParser("text2.txt")
reader.TextFieldType = FieldType.Delimited
reader.SetDelimiters(",")
currentrow = reader.ReadFields()
storageArray(4) = currentrow(0)
storageArray(4) = currentrow(1)
..... etc., etc.
当我尝试将一个数组的值分配到不同的数组时,我不断抛出System.NullReferenceException ...
我知道ReadFields()返回一个数组,所以我也尝试将每一行存储在一个锯齿状数组中,这会引发同样的错误。
作为对此的补充,我有更好的方法来做这件事吗?我读了很多关于将整个文件读入数组然后解析它的问题,但我似乎仍然无法将一个数组的值存储在另一个数组中...
先谢谢大家的帮助!
答案 0 :(得分:0)
要声明字符串数组,正确的语法如下
Dim storageArray(size) as String
其中 size 是您要在该数组中存储的元素数 所以上面的代码根本就没有编译。
但是在您的上下文中,您不知道此数组需要多大,因为您还没有读取该文件。在这种情况下,最好的方法是使用List(Of String)
,允许向List添加新元素,而无需重新定义数组
所以你的代码可以写成
Dim storageList = New List(Of String)()
Using reader As TextFieldParser = New TextFieldParser("text1.txt")
reader.TextFieldType = FieldType.Delimited
reader.SetDelimiters(",")
storageList.AddRange(reader.ReadFields())
End Using
Using reader As TextFieldParser = New TextFieldParser("text2.txt")
reader.TextFieldType = FieldType.Delimited
reader.SetDelimiters(",")
storageList.AddRange(reader.ReadFields())
End Using
....
请注意,完成使用后,需要处理像TextFieldParser这样的一次性对象。因此,将所有内容都包含在使用声明
中您可以使用List(Of strig)循环数据
for each data in storageList
Console.WriteLine(data)
next
或使用像数组一样的单个元素
Dim data = storageList(0)