Reputation: 5619
I have a problem that I am unable to reproduce in the lab / dev environment.
A beta user is reporting the following error during a file copy.
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\ProgramData....
The line of code in question is:
Directory.CreateDirectory(path);
Now I'm speculating what is going on here is this. Directory.CreateDirectory hands the operation off to the OS. On my test and dev machines there are plenty of resources and the OS creates the directory instantly.
On the beta users machine it is more resource challenged and it doesn't create the directory for a few milliseconds...perhaps even a full second.
In the meantime my application has moved on and is expecting the folder to be there. file.CopyTo(path, true);
My first question is if I am connecting the dots properly.
Second question is if so how should I handle?
sleep the app and monitor OS events for the folder created flag and then proceed. This seems to be a complex solution.
Sleep the app. Spin up a new thread that probes for the folder. When it exists kill thread then proceed. Perhaps not a new thread but same idea on main thread?
Upvotes: 3
Views: 1664
Reputation: 531
Your assessment is likely correct. There is probably a delay between when the Directory.CreateDirectory()
call returns and when the directory is actually created on the file system. This is discusses in this post here:
Directory.CreateDirectory Latency Issue?
A workaround would be to call Directory.Exists()
(MSDN) in a loop just after the call to CreateDirectory()
, something like this:
Direcotry.CreateDirectory(path);
int waitCount = 10;
do {
if (Directory.Exists(path))
{
break;
}
Thread.Sleep(100); // sleep 100ms
waitCount--;
if (waitCount <= 0)
{
throw new Exception("Failed to create directory");
}
} while(true);
The snipped is rough, but hopefully you get the idea.
Upvotes: 5
Reputation: 363
Use the FileSystemWatcher.Created Event to call you back when the directory is created. You will need to watch the parent directory for activity.
msdn sample code: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.created(v=vs.110).aspx
Upvotes: 5