c# - 为什么需要关闭 File.Create?

标签 c# .net

以下抛出异常“进程无法访问文件 'D:\MyDir\First.txt',因为它正被另一个进程使用。

static void Main(string[] args)
{
    Directory.CreateDirectory(@"D:\MyDir");
    File.Create(@"D:\MyDir\First.txt");
    File.WriteAllText(@"D:\MyDir\First.txt", "StackOverflow.com");
}

然而以下工作:

using (File.Create(@"D:\MyDir\First.txt"))
{ 
}

File.Create(@"D:\MyDir\First.txt").Close();

为什么? File.Create 中的哪些内容需要关闭?

最佳答案

File.Create 在这里所做的比您想象的要多。它不仅仅是创建文件,它还会将事件流返回到文件。但是,您没有对该流执行任何操作。后一个示例中的 using block 通过处理它来关闭该流。

另请注意,这是关于返回值的重要线索:

File.Create(@"D:\MyDir\First.txt").Close();

(当我第一次阅读您的问题时,实际上对我来说并不直观,但回过头来看这行代码实际上说明了一切。)

下一步,调用 File.WriteAllText 也比您想象的要多。根据the documentation ,它:

Creates a new file, writes the specified string to the file, and then closes the file.

所以看起来您的 File.Create 调用在这里并不是真正需要的。

关于c# - 为什么需要关闭 File.Create?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6072310/

相关文章:

c# - 在窗口上查找特定控件

c# - 获取未处理的异常 : System. Reflection.TargetParameterCountException:参数计数不匹配

c# - 使用 ASP.NET MVC3 处理注册向导的正确方法是什么?

枚举的 C# 显式初始化

c# - 什么是好的(如果有的话).NET Windows 自动化库?

c++ - 通过串口发送字符串

c# - C#是否可以将基类的实例用于子类的不同实例?

c# - 我应该强制异常(exception)来测试它们吗?

c# - Response.redirect URL在查询字符串中将空格编码为%20

c# - 当 TextBox 子项失去焦点时,ScrollViewer 跳到顶部