Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Then Deleting File Causes IOException

Tags:

c#

.net

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.

like image 237
Jim Avatar asked Aug 08 '12 10:08

Jim


4 Answers

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

like image 191
RB. Avatar answered Oct 20 '22 10:10

RB.


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.

like image 43
usr Avatar answered Oct 20 '22 09:10

usr


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.

like image 4
Matthew Watson Avatar answered Oct 20 '22 08:10

Matthew Watson


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");
like image 3
logicnp Avatar answered Oct 20 '22 08:10

logicnp