以下抛出异常“进程无法访问文件 '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/