Prevent Windows Explorer from interfering with directory operations
Sometimes after running this code, there is no "foo" directory left:
string folder = Path.Combine(Path.GetTempPath(), "foo");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
Process.Start(@"c:\windows\explorer.exe", folder);
Thread.Sleep(TimeSpan.FromSeconds(5));
Directory.Delete(folder, false);
Directory.CreateDirectory(folder);
Windows Explorer seems to keep the link to the folder, so the last CreateDirectory has nothing to do, but the original folder is deleted. How can I fix the code?
EDIT: I wish my question was clear. My goal is to create an empty directory "foo". If the directory already exists, I delete it and recreate it. The problem is that if Windows Explorer is looking for a directory, the CreateDirectory call sometimes fails. No exception is thrown; the directory just isn't created.
The above code reproduces the problem on my computer. Only the last two lines refer to my actual application. The previous lines are set up. Does "foo" always exist after running the code? This is not the case half the time on my computer.
I am currently manually deleting every file and subdirectory foo.
a source to share
Since you did not provide details (eg exceptions, errors), I assume this is the problem.
I think the problem is that explorer is still running when you run the command to delete the folder. This could be a blocking issue.
Directory.Delete(folder, false);
Either that, or there is another application accessing this folder or its subfolders or files if there are any by accident.
I would recommend that you do not touch the folder through explorer or any other application if possible, and wait for explorer to exit first before deleting the folder.
Process p = Process.Start(@"c:\windows\explorer.exe", folder);
Thread.Sleep(TimeSpan.FromSeconds(5));
p.WaitForExit(); //<-------
Directory.Delete(folder, false);
Also, do not ignore the exceptions and errors that you chose and insert them here if any.
Hope it helps.
a source to share