gpt4 book ai didi

c# - 如何处置 File.OpenRead()

转载 作者:太空狗 更新时间:2023-10-29 23:58:27 26 4
gpt4 key购买 nike

如何正确处理 File.OpenRead()。我目前正在使用以下代码?

using (BinaryReader br = new BinaryReader(File.OpenRead(path)))
{
myByte = br.ReadByte();
}

我在分析代码时在 Visual Studio 中得到以下信息:

Warning 1 CA2000 : Microsoft.Reliability : In method 'Program.Main(string[])', object 'File.OpenRead(path)' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'File.OpenRead(path)' before all references to it are out of scope.

最佳答案

乍一看,这看起来像是误报,因为处置 BinaryReader 也会处置 File.OpenRead 返回的 FileStream:

发件人:http://msdn.microsoft.com/en-us/library/azy2k2bx.aspx

When the disposing parameter is true, this method releases all resources held by any managed objects that this BinaryReader references. This method invokes the Dispose method of each referenced object.

但是,有一个极端情况,FileStream 确实没有被释放:当 BinaryReader 的构造函数抛出异常时!

解决方案:
编写代码的正确方法是这样的:

using (var fs = File.OpenRead(path))
{
BinaryReader br = new BinaryReader(fs);
myByte = br.ReadByte();
}

背景:
BinaryReader 仅包含对 FileStream 的引用,因此不需要释放。
Code Analysis 同意这一观点。


顺便说一句:将此解决方案用于可写流时,在流被释放之前刷新编写器很重要:

using (var fileStream = new FileStream(...))
{
var writer = new StreamWriter(fileStream);

writer.WriteLine(...);

writer.Flush(); // <-- Important
}

如果您忘记了这一点,您的流可能不会包含使用 StreamWriter 编写的所有内容。

关于c# - 如何处置 File.OpenRead(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5462203/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com