【问题标题】:Is Stream Binded?流绑定了吗?
【发布时间】:2025-12-17 12:10:02
【问题描述】:

我在尝试将我的流分配给另一个流并将其处理如下时遇到了一个异常

Stream str = new FileStream(somefile, FileMode.OpenOrCreate);
Stream newstr = str;
str.Dispose(); // I disposed only str and not new str

byte[] b = new byte[newstr.Length];// got exception here stating unable to access closed stream...

为什么……?我是 C# 和 Stream 的新手,其中 Stream 在命名空间 System.IO 中。

【问题讨论】:

    标签: c# winforms io stream


    【解决方案1】:

    是的,当您调用str.Dispose 时,newStr 也会被释放。这是因为 Stream 与 .NET 中的所有类一样,都是 reference types。当您编写Stream newstr = str 时,您并没有创建一个新的Stream,您只是创建了一个对相同 Stream 的新引用。

    正确的写法是:

    Stream str = new FileStream(somefile, FileMode.OpenOrCreate);
    int strLen = str.Length;
    str.Dispose(); 
    
    byte[] b = new byte[strLen];
    

    这将避免任何ObjectDisposedException。请注意intvalue type,因此当您编写int strLen = str.Length 时,您正在创建该值的新副本,并将其保存在变量strLen 中。因此,即使在 Stream 被释放后,您也可以使用该值。

    【讨论】: