zoukankan      html  css  js  c++  java
  • C# How to convert MessageBodyStream to MemoryStream?

        通过WCF服务从数据库取文档数据时,返回的是Stream对象,在DevExpress的PDFViewer显示时,用PDFViewer.LoadDocunent(Stream stream);方法时,报无法从MessageBodyStream转为Stream 的错误。

        最后在StackOverFlow上找到了答案

    不能通过转型,只能通过从Stream中读出数据,然后写入到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 ?

         下面是采纳的回答:

        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);
    未经作者允许,禁止转载
  • 相关阅读:
    [树形dp] Jzoj P5814 树
    [快速幂][数学][dp] Jzoj P5813 计算
    [差分] Jzoj P5812 区间
    [贪心][模拟] Jzoj P5811 简单的填数
    如何用c++发出音乐
    网络流初步详解
    【纪中模拟2019.08.01】【JZOJ2644】数列
    【纪中模拟2019.08.02】【JZOJ1308】取数游戏
    2019.08纪中 XC谈OI学习方法论
    C++STL容器
  • 原文地址:https://www.cnblogs.com/wangyangang/p/5736716.html
Copyright © 2011-2022 走看看