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?
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.
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 .
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.
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); }
Use this:
var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream);
This will convert Stream
to MemoryStream
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With