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.
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...
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With