We have a web server running hangfire that intermittently polls a shared network drive with a path example of:
\\SXXXXX\XXXXX$\XXX\
which intermittently throws a System.IO.DirectoryNotFoundException however the directory is created by the same piece of code.
It seems to run fine 8/10 times and on the 2 times it throws the exception it actually deletes the folder if its empty which is code that runs after the point of the exception?
Here's an example code block:
var downloadDirectory = "*OMITTED*
Directory.CreateDirectory(downloadDirectory);
TestDirectoryCreatedOnNetwork(downloadDirectory);
var dir = new DirectoryInfo(downloadDirectory);
if (dir.GetFiles().Count() == 0)
{
Directory.Delete(downloadDirectory);
return false;
}
Googling brought us to the idea that: Directory.CreateDirectory() would potentially suffer from latency so we added the following:
private static void TestDirectoryCreatedOnNetwork(string directory)
{
int waitCount = 10;
do
{
if (Directory.Exists(downloadDirectory))
{
break;
}
Thread.Sleep(10000); // sleep 100ms
waitCount--;
if (waitCount <= 0)
{
throw new Exception("Failed to create directory");
}
} while (true);
}
We know that the code works because of the fact that it runs 8/10 times so we're not really sure where to go from here.
Thanks!
As mentioned in the comments this was caused by poor network conditions, we've since moved the folder creation onto the actual web servers local drives and everything is now working