C#如何将System.Net.ConnectStream转换为byte [](数组)

时间:2012-09-28 19:14:44

标签: c# asp.net type-conversion

我试图将流(System.Net.ConnectStream)转换为字节数组。关于如何做到这一点的任何想法/例子?

3 个答案:

答案 0 :(得分:12)

Stream sourceStream = ... // the ConnectStream
byte[] array;
using (var ms = new MemoryStream())
{
    sourceStream.CopyTo(ms);
    array = ms.ToArray();
}

答案 1 :(得分:4)

试试这个......

    private static readonly object _lock = new object();

    public static byte[] readFullStream(Stream st)
    {
        try
        {
            Monitor.Enter(_lock);
            byte[] buffer = new byte[65536];
            Int32 bytesRead;
            MemoryStream ms = new MemoryStream();
            bool finished = false;
            while (!finished)
            {
                bytesRead = st.Read(buffer.Value, 0, buffer.Length);
                if (bytesRead > 0)
                {
                    ms.Write(buffer.Value, 0, bytesRead);
                }
                else
                {
                    finished = true;
                }
            }
            return ms.ToArray();
        }
        finally
        {
            Monitor.Exit(_lock);
        }
    }

答案 2 :(得分:0)

在Freeetje的一个回答中,有一个名为' ReadToEnd'的方法。对我来说就像一个魅力......

How do I get the filesize from the Microsoft.SharePoint.Client.File object?