Like in the topic: I want to read data from a file (from stream) into memory (memorystream) to improve my app speed. How to do it?
Stream can be called as the parent of memory stream class, as the MemoryStream inherits Stream class.. Streams involve three fundamental operations: You can read from streams. Reading is the transfer of data from a stream into a data structure, such as an array of bytes.
One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream. MemoryStream ms = new MemoryStream(bytes, writable: false); My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.
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 can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.
A few options:
Read it all into a byte array first...
byte[] data = File.ReadAllBytes(file); MemoryStream stream = new MemoryStream(data);
Or use .NET 4's CopyTo method
MemoryStream memoryStream = new MemoryStream(); using (Stream input = File.OpenRead(file)) { input.CopyTo(memoryStream); } memoryStream.Position = 0;
Or do it manually
MemoryStream memoryStream = new MemoryStream(); using (Stream input = File.OpenRead(file)) { byte[] buffer = new byte[32 * 1024]; // 32K buffer for example int bytesRead; while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, bytesRead); } } memoryStream.Position = 0;
If you can hold the entire file in memory, File.ReadAllBytes should work for you:
using (var ms = new MemoryStream(File.ReadAllBytes(file))) { // do work }
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