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

后端 未结 9 1061
天命终不由人
天命终不由人 2020-12-02 16:16

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

MemoryStream _ms;

public MyClass(string filePath)
{
    by         


        
相关标签:
9条回答
  • 2020-12-02 17:17

    You will have to read in all the data from the Stream object into a byte[] buffer and then pass that into the MemoryStream via its constructor. It may be better to be more specific about the type of stream object you are using. Stream is very generic and may not implement the Length attribute, which is rather useful when reading in data.

    Here's some code for you:

    public MyClass(Stream inputStream) {
        byte[] inputBuffer = new byte[inputStream.Length];
        inputStream.Read(inputBuffer, 0, inputBuffer.Length);
    
        _ms = new MemoryStream(inputBuffer);
    }
    

    If the Stream object doesn't implement the Length attribute, you will have to implement something like this:

    public MyClass(Stream inputStream) {
        MemoryStream outputStream = new MemoryStream();
    
        byte[] inputBuffer = new byte[65535];
        int readAmount;
        while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
            outputStream.Write(inputBuffer, 0, readAmount);
    
        _ms = outputStream;
    }
    
    0 讨论(0)
  • 2020-12-02 17:19

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 17:20
    public static void Do(Stream in)
    {
        _ms = new MemoryStream();
        byte[] buffer = new byte[65536];
        while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
            _ms.Write (buffer, 0, read);
    }
    
    0 讨论(0)
提交回复
热议问题