Creating a byte array from a stream

后端 未结 16 2952
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 23:35

    The one above is ok...but you will encounter data corruption when you send stuff over SMTP (if you need to). I've altered to something else that will help to correctly send byte for byte: '

    using System;
    using System.IO;
    
            private static byte[] ReadFully(string input)
            {
                FileStream sourceFile = new FileStream(input, FileMode.Open); //Open streamer
                BinaryReader binReader = new BinaryReader(sourceFile);
                byte[] output = new byte[sourceFile.Length]; //create byte array of size file
                for (long i = 0; i < sourceFile.Length; i++)
                    output[i] = binReader.ReadByte(); //read until done
                sourceFile.Close(); //dispose streamer
                binReader.Close(); //dispose reader
                return output;
            }'
    

提交回复
热议问题