Creating a byte array from a stream

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

    i was able to make it work on a single line:

    byte [] byteArr= ((MemoryStream)localStream).ToArray();
    

    as clarified by johnnyRose, Above code will only work for MemoryStream

    0 讨论(0)
  • 2020-11-21 23:52

    Just want to point out that in case you have a MemoryStream you already have memorystream.ToArray() for that.

    Also, if you are dealing with streams of unknown or different subtypes and you can receive a MemoryStream, you can relay on said method for those cases and still use the accepted answer for the others, like this:

    public static byte[] StreamToByteArray(Stream stream)
    {
        if (stream is MemoryStream)
        {
            return ((MemoryStream)stream).ToArray();                
        }
        else
        {
            // Jon Skeet's accepted answer 
            return ReadFully(stream);
        }
    }
    
    0 讨论(0)
  • 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<byte>();
    
            int b;
            while ((b = stream.ReadByte()) != -1)
                bytes.Add((byte)b);
    
            return bytes.ToArray();
        }
    }
    
    0 讨论(0)
  • 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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题