Creating a byte array from a stream

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

    I get a compile time error with Bob's (i.e. the questioner's) code. Stream.Length is a long whereas BinaryReader.ReadBytes takes an integer parameter. In my case, I do not expect to be dealing with Streams large enough to require long precision, so I use the following:

    Stream s;
    byte[] b;
    
    if (s.Length > int.MaxValue) {
      throw new Exception("This stream is larger than the conversion algorithm can currently handle.");
    }
    
    using (var br = new BinaryReader(s)) {
      b = br.ReadBytes((int)s.Length);
    }
    

提交回复
热议问题