如何检查 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/