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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…