直接Read(),可能读出的数据不全;
BinaryReader _br=new BinaryReader(stream);
byte[] _bs=new byte[_size];
_br.Read(_bs,0,_length);//可能读出结果不完整;
//-----------------------
byte[] _bs= _br.ReadBytes(_length);//读出结果完整;
查找c# source https://referencesource.microsoft.com/#mscorlib/system/io/binaryreader.cs,4f6cad84482876ff;readbytes使用do while进行了长度检查。
public virtual int Read(byte[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
if (m_stream==null) __Error.FileNotOpen();
return m_stream.Read(buffer, index, count);
}
public virtual byte[] ReadBytes(int count) {
if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
Contract.EndContractBlock();
if (m_stream==null) __Error.FileNotOpen();
if (count == 0) {
return EmptyArray<Byte>.Value;
}
byte[] result = new byte[count];
int numRead = 0;
do {
int n = m_stream.Read(result, numRead, count);
if (n == 0)
break;
numRead += n;
count -= n;
} while (count > 0);
if (numRead != result.Length) {
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
result = copy;
}
return result;
}