如何在方法返回之前关闭流?

时间:2015-11-28 22:04:46

标签: c# winforms

我收到System.IO.IOException因为我的文件被另一个进程使用了​​。是因为未封闭的流吗?如果是,我该怎么关闭呢?

public static ReportClass DeserializeRep(string FileWay)
{
    Stream stream = File.Open(FileWay, FileMode.Open);
    BinaryFormatter bformatter = new BinaryFormatter();
    return (ReportClass)bformatter.Deserialize(stream);
}


var CurRep = RequestSerializer.DeserializeRep(paths[selected]);

1 个答案:

答案 0 :(得分:4)

您应该使用using语句:

public static ReportClass DeserializeRep(string FileWay)
{
    using (Stream stream = File.Open(FileWay, FileMode.Open))
    {
        BinaryFormatter bformatter = new BinaryFormatter();
        return (ReportClass)bformatter.Deserialize(stream);
    }
}

还应该注意,using语句自动调用从IDisposible继承的任何对象的Dispose方法,在这种情况下关闭连接然后处理对象。

可以找到IDisposible文档here