Shyju
Shyju

Reputation: 218732

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 ?

Upvotes: 3

Views: 8738

Answers (4)

Synapse
Synapse

Reputation: 1

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, e.g.

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.

Upvotes: 0

Akshay
Akshay

Reputation: 61

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.

Upvotes: 6

CrazyDart
CrazyDart

Reputation: 3801

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);

Upvotes: 2

Oded
Oded

Reputation: 499002

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.

Upvotes: 1

Related Questions