Search code examples
c#.netfile-iostreammemorystream

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?


Solution

  • If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:

    public class MyClass
    { 
        Stream _s;
    
        public MyClass(Stream s) { _s = s; }
    }
    

    But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:

    public MyClass(Stream stream)
    {
        _ms = new MemoryStream();
        CopyStream(stream, _ms);
    }
    
    // Merged From linked CopyStream below and Jon Skeet's ReadFully example
    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[16*1024];
        int read;
        while((read = input.Read (buffer, 0, buffer.Length)) > 0)
        {
            output.Write (buffer, 0, read);
        }
    }