如何从vbTab分离的文本文件中将数据输入到数组中?

时间:2012-03-19 00:44:51

标签: vb.net file-io

我无法将.txt文件中的一组数据转换为数组,基本上,我在文本文件中的内容是:

Eddy vbtab 20
Andy vbtab 30 
James vbtab 20

等。

我想将名称设置为Names数组,将数字设置为数字数组。

现在我所做的是

strFilename = "CustomerPrices.txt"
If File.Exists(strFilename) Then
  Dim srReader As New StreamReader(strFilename)
  intRecords = srReader.ReadLine() 
  intRows = intRecords     

  For i = 0 To intRows - 1
    intLastBlank = strInput.IndexOf(vbTab)
    strName(intPrices) = strInput.Substring(0, intLastBlank)

    dblPrices(intPrices) = Double.Parse(strInput.Substring(intLastBlank + 1))

但是当我调试时遇到问题“对象引用没有设置为对象的实例”

有人能给我一些建议吗?

由于

1 个答案:

答案 0 :(得分:3)

单独的数组在这里可能是一个坏主意。他们按字段对数据进行分组,而按记录对数据进行分组几乎总是更好。你想要的是一个充满特定类型的集合的集合。去做这样的事情:

Public Class CustomerPrice
   Public Property Name As String
   Public Property Price As Decimal
End Class

Public Function ReadCustomerPrices(ByVal fileName As String) As List(Of CustomerPrice)
    Dim result As New List(Of CustomerPrice)()
    Using srReader As New StreamReader(fileName)
        Dim line As String
        While (line = srReader.ReadLine()) <> Nothing
            Dim data() As String = line.Split(vbTab)
            result.Add(new CustomerPrice() From {Name = data(0), Price = Decimal.Parse(data(1))})
        End While
    End Using
    Return result
End Function

此代码中值得注意的其他一些事情:

  • 使用块将保证文件关闭,即使抛出异常
  • 检查File.Exists()几乎不合适。这是浪费的代码,因为您仍然必须能够处理异常文件。
  • 使用金钱时,你几乎总是想要使用Decimal类型而不是Double
  • 此代码需要Visual Studio 2010 / .Net 4,并且直接在回复窗口中输入,因此可能包含错误,甚至是基本语法错误。