C# 如何将MessageBodyStream转换为MemoryStream?

C# 如何将MessageBodyStream转换为MemoryStream?,c#,memorystream,C#,Memorystream,我正在从WCF服务返回一个流,并试图将其转换为MemoryStream。但在使用WCF服务的web应用程序中,我得到的结果是“MessageBodyStream”,而我期望的结果是“System.IO.Stream”。如何将其转换为MemoryStream?属于流类型 您需要将整个流读取到MemoryStream中才能进行转换 我不知道这是否是您真正想要的,但您可以简单地将值分配给MemoryStream变量,singeMemoryStream继承自Stream有时流进来时,您不知道它们有多大,

我正在从WCF服务返回一个流,并试图将其转换为MemoryStream。但在使用WCF服务的web应用程序中,我得到的结果是“MessageBodyStream”,而我期望的结果是“System.IO.Stream”。如何将其转换为MemoryStream?

属于
流类型

您需要将整个流读取到
MemoryStream
中才能进行转换


我不知道这是否是您真正想要的,但您可以简单地将值分配给
MemoryStream
变量,singe
MemoryStream
继承自
Stream

有时流进来时,您不知道它们有多大,因此请使用以下代码:

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;
}
一旦你有了字节数组,你就可以把它转换成一个内存流

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

要将MessageBodyStream转换为MemoryStream,请执行以下步骤:

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.
你完了


希望这有帮助。

看起来示例代码中的缓冲区在内部循环中每次加长时都会加倍。所以不是

byte[] temp = new byte[readBuffer.Length * 2] 
加不是比乘好吗

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

理想情况下,我们可以使用一个变量,而不是硬编码的值,但我希望这能传达这一点。

谢谢您的回答。节省了很多时间。