My company\'s code base contains the following C# line:
bool pathExists = Directory.Exists(path);
At runtime, the string path
happ
There is no way to change the behavior of Directory.Exists
for this scenario. Under the hood it's making a synchronous request over the network on the UI thread. If the network connection hangs because of an outage, too much traffic, etc ... it will cause the UI thread to hang as well.
The best you can do is make this request from a background thread and explicitly give up after a certain amount of time elapses. For example
Func<bool> func = () => Directory.Exists(path);
Task<bool> task = new Task<bool>(func);
task.Start();
if (task.Wait(100)) {
return task.Value;
} else {
// Didn't get an answer back in time be pessimistic and assume it didn't exist
return false;
}
If general network connectivity is your primary problem, you could try testing the network connectivity prior to this:
[DllImport("WININET", CharSet = CharSet.Auto)]
static extern bool InternetGetConnectedState(ref int lpdwFlags, int dwReserved);
public static bool Connected
{
get
{
int flags = 0;
return InternetGetConnectedState(ref flags, 0);
}
}
Then determine if the path is a UNC path and return false if the network is offline:
public static bool FolderExists(string directory)
{
if (new Uri(directory, UriKind.Absolute).IsUnc && !Connected)
return false;
return System.IO.Directory.Exists(directory);
}
None of this helps when the host you're trying to connect to is offline. In that case you're still in for 2-minute network timeout.