Creating and deleting a file Causes IOException

The application should create a file in the directory, do something in the directory and then delete the file. For example, the source code is below:

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

If β€œsomething” is a process that requires a very short amount of time, File.Delete will raise an IOException (the file is being used by another process). According to another SO post: It is not possible to delete a directory using Directory.Delete (path, true) by calling Thread.Sleep (0) so that the previous process ends. However, even with

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

nevertheless, the same IOException will be thrown.

The solution I got is a while loop that tries to delete the file again before it is deleted. But I wonder if Theres is the best solution.

+8
c #
source share
4 answers

File.Create returns you a FileStream, which is an open handle to this file. Wrap the result of this call in the using block to close the handle in a deterministic way.

+16
source share

The File.Create method will create a file stream that you will need to properly dispose of. I suggest the following code:

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

Please note that this code exactly matches the one suggested in the MSDN documentation ...

+21
source share

Also note: if you do not want to write anything to a file, you can avoid "use" in two ways:

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

In case (2), it is safe to avoid using it because you are not doing anything to create an exception between creating and deleting it.

+4
source share

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

 using(FileStream fs = File.Create("textfile.txt")) {} File.Delete("textfile.txt"); 
+3
source share

All Articles