如何(快速)检查UNC路径可 [英] How to (quickly) check if UNC Path is available

查看:902
本文介绍了如何(快速)检查UNC路径可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查是否UNC路径可用?
我有一个检查过程约半分钟,如果份额的不可以可用的问题:

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)
//...

有没有检查,如果一个文件夹可用更快的方法?
我使用Windows XP和C#。

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

推荐答案

这个怎么样的一个快速和肮脏的方法来检查 - 运行Windows NET USE 命令和解析对于感兴趣的网络路径的线路输出(如 \\\\ vault2 )和确定。下面是输出的一个例子:

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.

这不是一个很.netish的解决方案,但它的速度非常快,有时是更重要: - )

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

和这里的code做它(LINQPad告诉我,只需要 150ms的,所以这是很好的)

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 = QuickBestGuessAboutAccessibilityOfPath(@"\\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;
}

或者,你也许可以去使用 WMI ,如提到的<一个HREF =htt​​p://stackoverflow.com/a/8993155/116891>这个答案以<一个href=\"http://stackoverflow.com/questions/8876022/how-to-ensure-network-drives-are-connected-for-an-application\">How确保网络驱动器连接为一个应用程序?

这篇关于如何(快速)检查UNC路径可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆