Error Message: System.NullReferenceException

nibsy

Well-known member
Joined
Aug 7, 2002
Messages
51
Location
Kent, UK
I cant see why I get the following error, on the highlighted line in the code below, when I try to open a file that does not exist:

An unhandled exception of type System.NullReferenceException occurred in WebTrendsLogs.exe

Additional information: Object reference not set to an instance of an object.


[VB]
Dim fsInput As FileStream
Try
Open the file.
fsInput = New FileStream(sreadFile, FileMode.Open, FileAccess.Read)

Try
srInput = New StreamReader(fsInput)
Read File.
sFileLine = srInput.ReadLine()
While Not IsNothing(sFileLine)
Append to array.
sContents.Add(sFileLine)
Read File.
sFileLine = srInput.ReadLine()
End While
Catch eIO As Exception
MessageBox.Show("Couldnt read the file " & sFile, "Error Message", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
srInput.Close()
End Try
Catch eFile As Exception
MessageBox.Show("Couldnt open file " & sFile, "Error Message", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
fsInput.Close()
End Try
[/VB]

Any assistance will be greatfully received, Thanks
 
Makes sense to me:

An instance of Filestream (with the name fsInput) can not be created.

An exception is thrown. (eFile)

In the finally block, there still is no instance of Filstream called fsInput. fsInput is still nothing.
 
Thanks Heiko,

I guess the best thing to do would not to error trap in this way, but to first check if the file exists (IO.File.Exists)?
 
Yes, do that, but also in the finally block, do a check for a null reference as follows:

Code:
If Not fsInput Is Nothing Then fsInput.Close()
 
you dont need quite so many Try / Catches in there , heres a simple example that has less lines of code and works without a problem :
Code:
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim sReader As StreamReader
        Try
            sReader = New StreamReader(New FileStream("C:\test.txt", FileMode.Open, FileAccess.Read))
            While Not sReader.Peek
                MessageBox.Show(sReader.ReadLine)
            End While
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            sReader.DiscardBufferedData()
            sReader.Close()
            sReader = Nothing
        End Try
    End Sub
 
Thanks all, I just thought I would post my working, streamlined code:

[VB]
Try
Open the file.
srInput = New StreamReader(New FileStream(sreadFile, _
FileMode.Open, FileAccess.Read))
Read the file.
sFileLine = srInput.ReadLine()
While Not IsNothing(sFileLine)
Append to array.
sContents.Add(sFileLine)
Read Line.
sFileLine = srInput.ReadLine()
End While
Catch ex As Exception
MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
Finally
If Not srInput Is Nothing Then
srInput.DiscardBufferedData()
srInput.Close()
srInput = Nothing
End If
End Try
[/VB]
 
Back
Top