在“文件”之后关闭文件

我检查文件是否存在

if(!File.Exists(myPath))
{
File.Create(myPath);
}

但是,当我用这个新创建的文件创建 StreamReader时,我得到一个错误,说

进程无法访问文件“[ my file path here ]”,因为它正被另一个进程使用。

没有一个 File.Close(myPath),我可以调用,以便它被创建后关闭,所以我如何释放这个资源,以便我可以打开它以后在我的程序?

208504 次浏览

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();

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 returns a FileStream object that you can call Close() on.

The function returns a FileStream object. So you could use it's return value to open your StreamWriter or close it using the proper method of the object:

File.Create(myPath).Close();

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
using(FileStream fs = File.Create(myPath))
using(StreamWriter writer = new StreamWriter(fs)){
// do your work here
}
}
File.WriteAllText(file,content)

create write close

File.WriteAllBytes--   type binary

:)