简体   繁体   中英

C# How to convert MessageBodyStream to MemoryStream?

I am returning a Stream from a WCF Service and trying to convert it to a MemoryStream.But in the web application where in consume the WCF service,I am getting the result as of "MessageBodyStream" where i was expecting "System.IO.Stream". How can i convert this to a MemoryStream ?

To convert MessageBodyStream to a MemoryStream, follow these steps:

MemoryStream stream = new MemoryStream();
messageStream.CopyTo(stream); // Assuming messageStream is your MessageBodyStream
stream.Position = 0; // Be sure to set the position to 0 before using it.

And you are done !!

Hope this helps.

Sometimes the streams come in and you dont know how big they are, for that use this code:

public static byte[] ReadToEnd(System.IO.Stream stream)
{
    long originalPosition = stream.Position;

    byte[] readBuffer = new byte[4096];

    int totalBytesRead = 0;
    int bytesRead;

    while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
    {
        totalBytesRead += bytesRead;

        if (totalBytesRead == readBuffer.Length)
        {
            int nextByte = stream.ReadByte();
            if (nextByte != -1)
            {
                byte[] temp = new byte[readBuffer.Length * 2];
                Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                readBuffer = temp;
                totalBytesRead++;
            }
        }
    }

    byte[] buffer = readBuffer;
    if (readBuffer.Length != totalBytesRead)
    {
        buffer = new byte[totalBytesRead];
        Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
    }
    return buffer;
}

Then once you have the byte array you can convert it to a memory stream...

    byte[] myBytes = ReadToEnd(theStream);
    Stream theMemStream = new MemoryStream(myBytes, 0, myBytes.Length);

Message.BodyStream is of type Stream .

You will need to read the whole stream into your MemoryStream in order to convert it.

I don't know if this is what you actually want, but you could be simply assign the value to a MemoryStream variable, singe MemoryStream inherits from Stream .

Looks like the buffer in example code will double in size each time it is lengthened in the inner loop. So instead of

byte[] temp = new byte[readBuffer.Length * 2] 

wouldn't it be better to add instead of multiply, eg

byte[] temp = new byte[readBuffer.Length + 4096]

Ideally we might use a variable instead of a hard coded value here, but I hope this conveys the point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM