Creating a byte array from a stream

后端 未结 16 2992
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 23:22

What is the prefered method for creating a byte array from an input stream?

Here is my current solution with .NET 3.5.

Stream s;
byte[] b;

using (         


        
16条回答
  •  名媛妹妹
    2020-11-21 23:49

    public static byte[] ToByteArray(Stream stream)
        {
            if (stream is MemoryStream)
            {
                return ((MemoryStream)stream).ToArray();
            }
            else
            {
                byte[] buffer = new byte[16 * 1024];
                using (MemoryStream ms = new MemoryStream())
                {
                    int read;
                    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    return ms.ToArray();
                }
            }            
        }
    

提交回复
热议问题