8

An application needs to create a file in a directory, do something in the directory, and then delete the file. For example, the source code below:

File.Create("textfile.txt");
// Do something here
File.Delete("textfile.txt");

If "something" is a process that only needs a very short amount of time, File.Delete will throw IOException (file is being used by another process). According to another SO post: Cannot delete directory with Directory.Delete(path, true), calling Thread.Sleep(0) should allow the previous process to finish. However, even with

File.Create("textfile.txt");
// Do something here
Thread.Sleep(0);
File.Delete("textfile.txt");

the same IOException is still be thrown.

The solution I got is a while-loop that try to delete the file repeatedly until it's deleted. But I'm wondering if theres' a better solution.

Community
  • 1
  • 1
Jim
  • 1,695
  • 2
  • 23
  • 42
  • 1
    Thanks for the very fast answers (and pointing out it's on MSDN. I'm certainly not feeling very bright right now). Gonna go with @usr because he's the first. But please accept the +1 as my thanks. – Jim Aug 08 '12 at 10:58

4 Answers4

21

The File.Create method will create a file-stream, which you will need to dispose of correctly. I suggest the following code:

using(FileStream fs = File.Create("textfile.txt"))
{
    // Do something here.
}
File.Delete("textfile.txt");

Note that this code is exactly as suggested in the MSDN documentation...

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
RB.
  • 36,301
  • 12
  • 91
  • 131
16

File.Create returns you a FileStream which represents an open handle to that file. Wrap the result of that call in a using-block to close the handle deterministically.

usr
  • 168,620
  • 35
  • 240
  • 369
4

Also note: If you do not want to write anything into the file, you can avoid the "using" in two ways:

(1) File.WriteAllText("textfile.txt", string.Empty);
(2) File.Create("textfile.txt").Dispose();

In case (2) it is safe to avoid the using because you are doing nothing that could throw an exception between creating it and disposing it.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
3

File.Create returns a FileStream which is an open handle to that file. Use this instead:

using(FileStream fs = File.Create("textfile.txt"))
{}

File.Delete("textfile.txt");
logicnp
  • 5,796
  • 1
  • 28
  • 32