Creating a byte array from a stream

后端 未结 16 2977
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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);
        }
    }
    

提交回复
热议问题