在 File.Create 之后关闭文件 [英] Closing a file after File.Create
问题描述
我用
if(!File.Exists(myPath))
{
File.Create(myPath);
}
但是,当我使用这个新创建的文件创建一个 StreamReader
时,我收到一个错误提示
However, when I go to create a StreamReader
with this newly created file, I get an error saying that
进程无法访问文件[我的文件路径]",因为它正被另一个进程使用.
The process cannot access the file '[my file path here]' because it is being used by another process.
没有我可以调用的 File.Close(myPath)
以便在创建后关闭它,那么我如何释放此资源以便稍后在我的程序?
There isn't a File.Close(myPath)
that I can call so that it is closed after being created, so how do I free this resource so that I can open it later in my program?
推荐答案
File.Create(string)
返回 FileStream<的一个实例/code> 类
.您可以调用 Stream.Close()
方法以关闭它并释放它正在使用的资源:
File.Create(string)
returns an instance of the FileStream
class. You can call the Stream.Close()
method on this object in order to close it and release resources that it's using:
var myFile = File.Create(myPath);
myFile.Close();
但是,由于 FileStream
实现了 IDisposable
,您可以利用 using
声明(通常是处理此类情况的首选方式).这将确保流在完成后关闭并正确处理:
However, since FileStream
implements IDisposable
, you can take advantage of the using
statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:
using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}
这篇关于在 File.Create 之后关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!