c# - 如何(快速)检查 UNC 路径是否可用

标签 c# unc

如何检查 UNC 路径是否可用? 我有一个问题,如果共享可用,检查需要大约半分钟:

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

if (fi.Exists)
//...

有没有更快的方法来检查文件夹是否可用? 我正在使用 Windows XP 和 C#。

最佳答案

这是一种快速而肮脏的检查方式 - 运行 Windows net use 命令并解析具有感兴趣网络路径的行的输出(例如 \\vault2) 和确定。这是输出示例:

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 的解决方案,但它非常快,有时这更重要 :-)。

这是执行此操作的代码(LINQPad 告诉我它只需要 150 毫秒,这很好)

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;
}

或者您可能会选择使用 WMI 的路线,如 this answer 中提到的至 How to ensure network drives are connected for an application?

关于c# - 如何(快速)检查 UNC 路径是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5152647/

相关文章:

c# - 有条件地加入 LINQ?

c# - 什么时候结构是答案?

java - 如何使用 Java 访问安装在 Windows 上的驱动器?

c# - 我无法从 C# 访问 unc 路径。获取访问权限被拒绝

c# - 从本地路径或映射路径获取 UNC 路径

c# - 如何像在 NoSQL 中那样实现 select ...?

c# - 输入字符串的格式不正确错误 #2

c# - Oracle Odp.Net 在调用无效包中的过程时出现未报告的错误

c++ - 正则表达式:拆分到路径的最后一次出现

python - 安装 win_unc 库时出现 unicode 错误