开发者

Why is File.Create needed to be closed?

The following throws an exception "The proces开发者_如何转开发s cannot access the file 'D:\MyDir\First.txt' because it is being used by another process."

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

However following works:

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

or

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

Why? What in File.Create needs to be closed?


File.Create is doing more than you think here. It's not just creating the file, it's also returning an active stream to the file. However, you're not doing anything with that stream. The using block in your latter example closes that stream by disposing it.

Note also that this is a significant clue about the return value:

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

(It actually wasn't intuitive to me when I first read your question, but looking back at it this line of code actually says it all.)

Your next step, calling File.WriteAllText also does more than you think. According to the documentation, it:

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

So it would seem that your File.Create call isn't really needed here anyway.


Because it opens a file stream, which is a class managing some operating system low-level resources and those must be released in order to let other operations in other threads, and even in other applications, access to the file.


You don't actually need to call File.Create() to then be able to call File.WriteAllText().

File.WriteAllText() will create a new file and write to it then close the file all in one handy method.

If the file already exists it'll be overwritten.


The MSDN docs for File.Create() explain this:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

Basically until the file create is closed the file cannot be access by another process (in this case your attempt to write to it).


File.Create(string) returns a FileStream object that holds the file open. Even though you are not keeping a reference to FileStream object in a variable, it still exists. The object is eligable for garbage collection, and when that happens the file will be closed, but there is no predicting when the garbage collection will take place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜