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开发者_StackOverflow中文版 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*/
}
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);
}
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*/
}
Use a finally block, this will execute whether an exception occurred or not:
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);
}
}
catch (Exception ex)
{
/*handle Exception*/
}
finally
{
if (stream != null)
stream.Close();
}
SavedEventSet sES;
OpenFileDialog oFD = new OpenFileDialog();
BinaryFormatter bF;
try
{
oFD.InitialDirectory = this.path;
oFD.Title = "Open Event Saved File.";
oFD.ShowDialog();
if(oFD.FileName.Contains(".sav"))
{
using(Stream stream = File.Open(oFD.FileName, FileMode.Open))
{
bF = new BinaryFormatter();
sES = (SavedEventSet)bF.Deserialize(stream);
stream.Close();
}
}
}
catch (Exception ex)
{
/*handle Exception*/
}
精彩评论