Check if server path is available as file share in C#

deadlydog picture deadlydog · Oct 1, 2013 · Viewed 15.1k times · Source

I want to quickly check if a file share is available in C#, but without knowing anything about the directories that might be on the network share. I have found these posts 1 2 3 that show how to check if a network directory is available, but they all assume I know the directory share that I want to check if exists. That is, they want to check if \\SomeServer\SomeDirectory is available, but I just want to check if \\SomeServer is available.

For a little more detail about what I'm trying to do, I prompt the user for a SQL server to connect to, and they give me an address such as "SQL001"; obviously this address is only valid when on our internal network. With this address I'm able to connect to the server and its databases. Now, I give them the option to backup a database, and want the OpenFileDialog to have the InitialDirectory set to "\\SQL001" so they can quickly access a shared folder on that server and back the database up on the remote server.

If I set "\\SQL001" as the OpenFileDialog's InitialDirectory, everything works fine, however if they mistyped and put "\\SQL002" (which doesn't exist), or maybe try and use the tool when off the internal network, then the OpenFileDialog's ShowDialog function throws an error. So I want to check and make sure that the file share is available first, and if not I won't set the InitialDirectory.

Using Directory.Exists("\\SQL001") always returns false unfortunately. If I do Directory.Exists("\\SQL001\Backups") it works, but we have many different SQL servers and they don't all have a share called "Backups", so that is not reliable. I can also use Directory.Exists("\\SQL001\c$\") which works for me, but many employees will not have permissions to the root C:\, but will have permissions for the network shares, so that is not a good alternative either.

So my question is, assuming the user has permissions to a file share, how can I check that the file share is available? Also, I don't want to force the user to map "\\SQL001" as a network drive either.

The only solution I can see right now is to just call the OpenFileDialog's ShowDialog function and catch the specific exception, wipe out the InitialDirectory and then call ShowDialog again. It'll work, but feels a bit hacky, so I'm hoping for a better solution.

Answer

Allan Elder picture Allan Elder · Oct 1, 2013

A valid UNC path must contain a minimum of two components; the \SERVERNAME\SHARE; Directory.Exists will return false if that condition isn't met.

To determine if the machine that is identified by SERVERNAME exists, you could use GetHostByName

http://msdn.microsoft.com/en-us/library/system.net.dns.gethostbyname.aspx

That still won't tell you if the machine is down, though.