Creating a byte array from a stream

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

    You can even make it fancier with extensions:

    namespace Foo
    {
        public static class Extensions
        {
            public static byte[] ToByteArray(this Stream stream)
            {
                using (stream)
                {
                    using (MemoryStream memStream = new MemoryStream())
                    {
                         stream.CopyTo(memStream);
                         return memStream.ToArray();
                    }
                }
            }
        }
    }
    

    And then call it as a regular method:

    byte[] arr = someStream.ToByteArray()
    

提交回复
热议问题