Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a MemoryStream from a Stream in .NET?

I have the following constructor method which opens a MemoryStream from a file path:

MemoryStream _ms;  public MyClass(string filePath) {     byte[] docBytes = File.ReadAllBytes(filePath);     _ms = new MemoryStream();     _ms.Write(docBytes, 0, docBytes.Length); } 

I need to change this to accept a Stream instead of a file path. Whats the easiest/most efficient way to get a MemoryStream from the Stream object?

like image 384
fearofawhackplanet Avatar asked Jul 09 '10 12:07

fearofawhackplanet


People also ask

How do I get bytes from MemoryStream?

To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.

Does MemoryStream need to be disposed?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .

What is the difference between stream and MemoryStream?

You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.


2 Answers

In .NET 4, you can use Stream.CopyTo to copy a stream, instead of the home-brew methods listed in the other answers.

MemoryStream _ms;  public MyClass(Stream sourceStream)      _ms = new MemoryStream();     sourceStream.CopyTo(_ms); } 
like image 199
Phil Devaney Avatar answered Oct 21 '22 09:10

Phil Devaney


Use this:

var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); 

This will convert Stream to MemoryStream.

like image 23
Sahil Jain Avatar answered Oct 21 '22 08:10

Sahil Jain