Reputation: 558
I came across an exception while trying to do my stream to assign to another and dispose it as below
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...
Why......? I am new to C# and Stream
where Stream
is in namespace System.IO
.
Upvotes: 1
Views: 40
Reputation: 149020
Yes, when you call str.Dispose
, newStr
is also disposed. This is because Stream
, like all classes in .NET, are reference types. When you write Stream newstr = str
, you are not creating a new Stream
, you are simply creating a new reference to the same Stream
.
The correct way to write this would be:
Stream str = new FileStream(somefile, FileMode.OpenOrCreate);
int strLen = str.Length;
str.Dispose();
byte[] b = new byte[strLen];
This will avoid any ObjectDisposedException
's. Note that int
is a value type, so when you write int strLen = str.Length
you are creating a new copy of the value, and saving it in the variable strLen
. So even after the Stream
is disposed, you can use that value.
Upvotes: 3