Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream in Using Statement - Do I need to call close()

When using a memory stream in a using statement do I need to call close? For instance is ms.Close() needed here?

  using (MemoryStream ms = new MemoryStream(byteArray))      {         // stuff         ms.Close();      } 
like image 611
AJM Avatar asked Aug 15 '12 11:08

AJM


People also ask

Do you need to close a MemoryStream?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory.

Does using statement close stream?

using ensures that Dispose() will be called, which in turn calls the Close() method. You can assume that all kinds of Streams are getting closed by the using statement.

How do I use MemoryStream?

Empty memory streams are resizable, and can be written to and read from. If a MemoryStream object is added to a ResX file or a . resources file, call the GetStream method at runtime to retrieve it. If a MemoryStream object is serialized to a resource file it will actually be serialized as an UnmanagedMemoryStream.

What is the difference between MemoryStream and FileStream?

As the name suggests, a FileStream reads and writes to a file whereas a MemoryStream reads and writes to the memory. So it relates to where the stream is stored.


2 Answers

No, it's not.

using ensures that Dispose() will be called, which in turn calls the Close() method.

You can assume that all kinds of Streams are getting closed by the using statement.

From MSDN:

When you use an object that accesses unmanaged resources, such as a StreamWriter, a good practice is to create the instance with a using statement. The using statement automatically closes the stream and calls Dispose on the object when the code that is using it has completed.

like image 103
sloth Avatar answered Nov 08 '22 02:11

sloth


When using a memory stream in a using statement do I need to call close?

No, you don't need. It will be called by the .Dispose() method which is automatically called:

using (MemoryStream ms = new MemoryStream(byteArray))  {       // stuff  } 
like image 32
Darin Dimitrov Avatar answered Nov 08 '22 01:11

Darin Dimitrov