最近涉及到流的获取与转化,终于要还流的债了。
百度了一下,看到这样的两条回复,于是好奇心,决定看看两种写法的源码差异。
先来看看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 >