Creating a byte array from a stream

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

    This is the function which I am using, tested and worked well. please bear in mind that 'input' should not be null and 'input.position' should reset to '0' before reading otherwise it will break the read loop and nothing will read to convert to array.

        public static byte[] StreamToByteArray(Stream input)
        {
            if (input == null)
                return null;
            byte[] buffer = new byte[16 * 1024];
            input.Position = 0;
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                byte[] temp = ms.ToArray();
    
                return temp;
            }
        }
    

提交回复
热议问题