Search code examples
c#unc

How to (quickly) check if UNC Path is available


How can I check if a UNC Path is available? I have the problem that the check takes about half a minute if the share is not available :

var fi = new DirectoryInfo(@"\\hostname\samba-sharename\directory");

if (fi.Exists)
//...

Is there a faster way to check if a folder is available? I'm using Windows XP and C#.


Solution

  • How's this for a quick and dirty way to check - run the windows net use command and parse the output for the line with the network path of interest (e.g. \\vault2) and OK. Here's an example of the output:

    C:\>net use
    New connections will be remembered.
    
    Status       Local     Remote                    Network
    
    -------------------------------------------------------------------------------
    OK           O:        \\smarty\Data       Microsoft Windows Network
    Disconnected P:        \\dummy\Data       Microsoft Windows Network
    OK                     \\vault2\vault2           Microsoft Windows Network
    The command completed successfully.
    

    It's not a very .netish solution, but it's very fast, and sometimes that matters more :-).

    And here's the code to do it (and LINQPad tells me that it only takes 150ms, so that's nice)

    void Main()
    {
        bool available = QuickBestGuessAboutAccessibilityOfNetworkPath(@"\\vault2\vault2\dir1\dir2");
        Console.WriteLine(available);
    }
    
    public static bool QuickBestGuessAboutAccessibilityOfNetworkPath(string path)
    {
        if (string.IsNullOrEmpty(path)) return false;
        string pathRoot = Path.GetPathRoot(path);
        if (string.IsNullOrEmpty(pathRoot)) return false;
        ProcessStartInfo pinfo = new ProcessStartInfo("net", "use");
        pinfo.CreateNoWindow = true;
        pinfo.RedirectStandardOutput = true;
        pinfo.UseShellExecute = false;
        string output;
        using (Process p = Process.Start(pinfo)) {
            output = p.StandardOutput.ReadToEnd();
        }
        foreach (string line in output.Split('\n'))
        {
            if (line.Contains(pathRoot) && line.Contains("OK"))
            {
                return true; // shareIsProbablyConnected
            }
        }
        return false;
    }
    

    Or you could probably go the route of using WMI, as alluded to in this answer to How to ensure network drives are connected for an application?