Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Directory.Exists on a network folder when the network is down

My company's code base contains the following C# line:

bool pathExists = Directory.Exists(path);

At runtime, the string path happens to be the address of a folder on the company's intranet - something like \\company\companyFolder. When the connection from my Windows machine to the intranet is up, this works fine. However, when the connection goes down (as it did today), executing the line above causes the application to freeze completely. I can only shut the application down by killing it with the Task Manager.

Of course, I would rather have Directory.Exists(path) return false in this scenario. Is there a way to do this?

like image 848
user181813 Avatar asked Dec 08 '11 17:12

user181813


2 Answers

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;
}
like image 51
JaredPar Avatar answered Sep 22 '22 04:09

JaredPar


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.

like image 40
csharptest.net Avatar answered Sep 24 '22 04:09

csharptest.net