在vb中使用StreamReader的NullReferenceException

时间:2014-11-22 22:43:34

标签: vb.net nullreferenceexception

Imports System.IO

Module Module1
Structure TownType
    Dim Name As String
    Dim County As String
    Dim Population As String
    Dim Area As String
End Structure

Dim reader As StreamReader
Dim writer As StreamWriter

Sub Main()
    Dim FileName As String = "C:\Users\Desktop\Towns.csv"
    reader = New StreamReader(FileName)
    Dim Count As Integer
    Dim Line As String
    Dim TownList() As TownType
    Dim MyFormat As String = "{0,  -22} {1,  -16} {2,  -8} {3,  -8}"

    Do Until reader.EndOfStream = True
        Line = reader.ReadLine
        Dim record = Line.Split(",")
        TownList(Count).Name = record(0)
        TownList(Count).County = record(1)
        TownList(Count).Population = record(2)
        TownList(Count).Area = record(3)
        Console.WriteLine(String.Format(MyFormat, TownList(Count).Name, TownList(Count).County, TownList(Count).Population, TownList(Count).Area))
        Count = Count + 1
    Loop
    Console.ReadLine()
End Sub

End Module

我正在尝试从文件中读取内容,并在控制台上以基于表格的格式显示它们,但是这行代码就行了“TownList(Count).Name = record(0) '我收到错误NullReferenceExceptionErrorWasUnhandled并且我不知道为什么?

1 个答案:

答案 0 :(得分:1)

您必须先初始化阵列。例如:

Dim TownList(10) As TownType

然后你必须初始化每个TownList

Do Until reader.EndOfStream = True
    Line = reader.ReadLine
    Dim record = Line.Split(",")
    Dim tt As New TownType()
    tt.Name = record(0)
    ' .... '
    TownList(Count) = tt 
    ' .....'

但是,由于你不知道数组的最终大小,你应该使用List(Of TownType)代替。

Dim TownList As New List(Of TownType)
Do Until reader.EndOfStream = True
    Line = reader.ReadLine
    Dim record = Line.Split(",")
    Dim tt As New TownType()
    tt.Name = record(0)
    ' .... '
    TownList.Add(tt)
    ' .....'

如果您需要阵列,最后可以使用TownList.ToArray