C# binaryReader.Read()和ReadBytes()

43 篇文章 0 订阅

直接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;
        }
 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值