The issue might become clearer if you split your file-open logic across two lines:
try
{
var fs = File.Open((sender).fileName, FileMode.Open);
br = new BinaryReader(fs);
}
finally
{
br.Dispose();
}
When the File.Open
call fails, the exception is thrown without anything being assigned to the br
field. When you attempt to dispose it in the finally
block, it would still be null
, thus your exception.
Edit: The way I would suggest fixing this:
try
{
using (FileStream fs = File.Open(sender.fileName, FileMode.Open))
using (BinaryReader br = new BinaryReader(fs))
{
//read in header from file.
if ( /*header shows wrong file format*/ )
{
isWrongFormat = true;
MessageBox.Show("Wrong format.");
ErrorInFileReadEventHandler(this, null);
}
else
{
//read rest of file.
SuccessfulFileReadEventHandler(this, null);
}
}
}
catch
{
MessageBox.Show("Couldn't access.");
ErrorInFileReadEventHandler(this, null);
}
In the process, I've demoted your BinaryReader
from a field to a local variable. Since you're only accessing it within the OpenFile
method (and disposing it before returning), there's no need for its reference to persist outside the method.