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.

1
  • 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. Commented Aug 8, 2012 at 10:58

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.