Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

c# - 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(@"\hostnamesamba-sharenamedirectory");

if (fi.Exists)
//...

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:        \smartyData       Microsoft Windows Network
Disconnected P:        \dummyData       Microsoft Windows Network
OK                     \vault2vault2           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(@"\vault2vault2dir1dir2");
    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('
'))
    {
        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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...