Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load entire stream into MemoryStream?

Tags:

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?

like image 740
apocalypse Avatar asked Jul 09 '12 14:07

apocalypse


People also ask

What is the difference between stream and MemoryStream?

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.

How do I save files to my memory stream?

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.

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 .

How do I reuse 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.


2 Answers

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; 
like image 190
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet


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 } 
like image 30
Austin Salonen Avatar answered Sep 21 '22 19:09

Austin Salonen