Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing a stream after an exception

I open a stream and then deserialize the data in the stream. However, I added a member to the SavedEventSet object so now when I try to open an old file, it throws the exception on the deserialization line.

This is fine with me (for now) but the problem is that I handle the exception, but never close the stream (because the exception occurred before I close the stream), so when I try to open the file again, it won't let me because it is in use.

How do I close the stream after this exception? If I put stream.Close() in either the catch or the finally, it complains about trying to access an unassigned local variable. Seems like bad practice to just open a random file I know is there. Is there any way to open a stream in a way that would be similar to an empty constructor so it will look like it is assigned?

Thanks

SavedEventSet sES;
OpenFileDialog oFD = new OpenFileDialog();
Stream stream;
BinaryFormatter bF;

try
{
    oFD.InitialDirectory = this.path;
    oFD.Title = "Open Event Saved File.";
    oFD.ShowDialog();

    if(oFD.FileName.Contains(".sav"))
    {
        stream = File.Open(oFD.FileName, FileMode.Open);
        bF = new BinaryFormatter();

        sES = (SavedEventSet)bF.Deserialize(stream);
        stream.Close();

    }
}
catch (Exception ex)
{
    stream.Close();
    /*handle Exception*/
}
like image 776
EatATaco Avatar asked Jan 21 '10 22:01

EatATaco


2 Answers

You can use a using block, which will automatically close the stream, even if there's an exception:

using(Stream stream = File.Open(oFD.FileName, FileMode.Open))
{
    bF = new BinaryFormatter();

    sES = (SavedEventSet)bF.Deserialize(stream);
}
like image 156
ShZ Avatar answered Sep 21 '22 13:09

ShZ


Set stream to null before the try block.

In your catch check if stream is not null, if not then close the stream.

  SavedEventSet sES;
  OpenFileDialog oFD = new OpenFileDialog();
  Stream stream = null;
  BinaryFormatter bF;

  try
  {
    oFD.InitialDirectory = this.path;
    oFD.Title = "Open Event Saved File.";
    oFD.ShowDialog();

    if (oFD.FileName.Contains(".sav"))
    {
      stream = File.Open(oFD.FileName, FileMode.Open);
      bF = new BinaryFormatter();

      sES = (SavedEventSet)bF.Deserialize(stream);
      stream.Close();

    }
  }
  catch (Exception ex)
  {
    if (stream != null)
      stream.Close();
    /*handle Exception*/
  }
like image 44
Daniel Avatar answered Sep 21 '22 13:09

Daniel