2019.04.19 读书笔记 比较File.OpenRead()和File.ReadAllBytes()的差异

本文探讨了C#中File.OpenRead()和File.ReadAllBytes()的区别,通过源码分析指出,OpenRead()可能会导致大文件读取不完整,而ReadAllBytes()在文件超过2GB时会抛出异常。建议在确定文件大小不会超过2GB时谨慎选择使用方式。
摘要由CSDN通过智能技术生成

最近涉及到流的获取与转化,终于要还流的债了。

百度了一下,看到这样的两条回复,于是好奇心,决定看看两种写法的源码差异。

先来看看OpenRead()

public static FileStream OpenRead(string path) => 
    new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

//构造函数又调用了其他构造函数,继续深入
[SecuritySafeCritical]
public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, 0x1000, FileOptions.None, Path.GetFileName(path), false)
{
}
//调用了Init 初始化
[SecurityCritical]
internal FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, string msgPath, bool bFromProxy)
{
    Win32Native.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
    this.Init(path, mode, access, 0, false, share, bufferSize, options, secAttrs, msgPath, bFromProxy, false, false);
}

//读取数据到流中,过程就没什么可以看的了
[SecuritySafeCritical]
private unsafe void Init(string path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs, string msgPath, bool bFromProxy, bool useLongPath, bool checkHost)
{
    int num;
    if (path == null)
    {
        throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    FileSystemRights rights2 = (FileSystemRights) rights;
    this._fileName = msgPath;
    this._exposedHandle = false;
    FileShare share2 = share & ~FileShare.Inheritable;
    string paramName = null;
    if ((mode < FileMode.CreateNew) || (mode > FileMode.Append))
    {
        paramName = "mode";
    }
    else if (!useRights && ((access < FileAccess.Read) || (access > FileAccess.ReadWrite)))
    {
        paramName = "access";
    }
    else if (useRights && ((rights2 < FileSystemRights.ListDirectory) || (rights2 >
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值