tags:

views:

52

answers:

2

I'm trying to get a list of all shared folders available on a local intranet server.

The System.IO.Directory.GetDirectories() works fine for a path like \\myServer\myShare, however I'm getting an exception for a path like \\myServer:

Unhandled Exception: System.ArgumentException: The UNC path should be of the form \server\share.

Is there a way to get a list all shared folders for a server? Ultimately I'm looking for a method that can handle both scenarios based on a given path - returning a list of all shares for a given server and returning a list of all subdirectories for a given network shared folder.

+2  A: 

Here's a technique that uses System.Management (add a reference to this assembly):

using (ManagementClass shares = new ManagementClass(@"\\NameOfTheRemoteComputer\root\cimv2", "Win32_Share", new ObjectGetOptions())) {
    foreach (ManagementObject share in shares.GetInstances()) {
        Console.WriteLine(share["Name"]);
    }
}

Appropriate permissions are required.

Bradley Smith
Thanks, Bradley. Your technique worked fine for enumerating shares on my local machine, however it gave me `System.Management.ManagementException: Access denied` exception when I tried to access server on a local network. On the same time the other solution (uses P/Invoke) worked fine for the same server.
Michael Narinsky
Yeah, I checked it out and you're right. I think there is more to WMI than meets the eye - including the need to work with the ConnectionOptions and ManagementScope classes in a certain way in order to access remote computers. I'm sure it's possible, but at this stage I don't have the experience to describe how to do it.
Bradley Smith
+2  A: 

I think this is what you are looking for http://www.codeproject.com/KB/IP/networkshares.aspx

ajay_whiz
Thanks, this worked for me. I ended up writing a method that extends System.IO.Directory.GetDirectories(). It uses regular expressions to figure out what kind of path is given (//server/share or just //server) and then calls either Directory.GetDirectories() or the CodeProject library respectively.
Michael Narinsky