32

The following throws an exception "The process 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?

Kang
  • 545
  • 1
  • 7
  • 15
  • possible duplicate of [File being used by another process after using File.Create()](http://stackoverflow.com/questions/2781357/file-being-used-by-another-process-after-using-file-create) – bluish Jun 17 '14 at 07:20

5 Answers5

47

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.

David
  • 208,112
  • 36
  • 198
  • 279
22

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
11

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.

Kev
  • 118,037
  • 53
  • 300
  • 385
10

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).

Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
8

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.

Jeffrey L Whitledge
  • 58,241
  • 9
  • 71
  • 99