我打开一个流,然后反序列化流中的数据。但是,我在SavedEventSet对象中添加了一个成员,所以现在当我尝试打开一个旧文件时,它会在反序列化行上抛出异常。
这对我来说没问题(现在),但问题是我处理异常,但从不关闭流(因为异常发生在我关闭流之前),所以当我再次尝试打开文件时,它不会让我因为它正在使用中。
如何在此异常后关闭流?如果我将stream.Close()放在catch或finally中,它会抱怨尝试访问未分配的局部变量。看起来不好的做法就是打开我知道的随机文件。有没有办法以类似于空构造函数的方式打开流,所以它看起来像是被分配了?
由于
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*/
}
答案 0 :(得分:27)
你可以使用using块,它会自动关闭流,即使有异常:
using(Stream stream = File.Open(oFD.FileName, FileMode.Open))
{
bF = new BinaryFormatter();
sES = (SavedEventSet)bF.Deserialize(stream);
}
答案 1 :(得分:6)
在try块之前将stream设置为null。
在catch中检查stream是否为null,否则关闭流。
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*/
}
答案 2 :(得分:4)
使用finally块,这将执行是否发生异常:
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();
}
答案 3 :(得分:0)
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*/
}