Jim
Jim

Reputation: 1735

Creating Then Deleting File Causes IOException

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.

Upvotes: 8

Views: 2969

Answers (4)

Matthew Watson
Matthew Watson

Reputation: 109852

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.

Upvotes: 4

RB.
RB.

Reputation: 37222

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

Upvotes: 21

logicnp
logicnp

Reputation: 5836

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

Upvotes: 3

usr
usr

Reputation: 171236

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.

Upvotes: 16

Related Questions