Creating a byte array from a stream

后端 未结 16 3185
爱一瞬间的悲伤
爱一瞬间的悲伤 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:53

    You can use this extension method.

    public static class StreamExtensions
    {
        public static byte[] ToByteArray(this Stream stream)
        {
            var bytes = new List();
    
            int b;
            while ((b = stream.ReadByte()) != -1)
                bytes.Add((byte)b);
    
            return bytes.ToArray();
        }
    }
    

提交回复
热议问题