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) //...
Is there a faster way to check if a folder is available? I'm using Windows XP and C#.
to get the UNC path you don't need any code. There you should see the shared folders of the computer (share name and location). Just replace the <computername> with the name of your computer with the file.
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.
CMD does not support UNC paths as current directories. The Pushd command automatically maps a drive and navigates to it. If you run the "net use" command after you run Pushd, you'll see a new drive mapping.
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.
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(@"\\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; }
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With