Our virtual home

Get the local mapped network drives using WMI

Today I helped a coworker to get the local mapped network drives using WMI instead of COM Interop/native windows API. Just to keep the code as a reminder and help others with the same problem I provide it here.

The result of the code below is in general the same you will get if you hit the "net use" command at the windows command shell prompt. For further infos and reading I suggest http://msdn2.microsoft.com/en-us/library/aa394173.aspx (Win32_LogicalDisk; MSDN WMI Reference); for immediate results of query the WMI you should use Scriptomatic (download from http://www.microsoft.com/downloads/details.aspx?familyid=09DFC342-648B-4119-B7EB-783B0F7D1178&displaylang=en).

Little bit optimization is yet possible providing the drive type in the WQL as a where clause parameter, so here it is:

/// Container for Share entries
public struct SharePathEntry
  public string Name;
  public string Path;
  public SharePathEntry(string n, string p) {
    Name = n;
    Path = p;

// for other types see: http://msdn2.microsoft.com/en-us/library/aa394173.aspx
const int NetworkDriveType = 4;

public static List GetLocalShares()
  List allLocalShares = new List(); // a container 

  WqlObjectQuery objectQuery = new WqlObjectQuery("select DriveType,DeviceID,ProviderName from Win32_LogicalDisk");
  ManagementScope scope = new ManagementScope(@"\\.\root\cimv2"); // local WMI namespace
  scope.Options.Impersonation = ImpersonationLevel.Impersonate; 
  scope.Options.EnablePrivileges = true; 
  ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, objectQuery);
  foreach (ManagementObject share in searcher.Get())
    int driveType = Convert.ToInt32(share["DriveType"]);
    if (driveType== NetworkDriveType) {
      object objName = share["DeviceID"];
      object objPath = share["ProviderName"];
      if (null != objName && null != objPath)
        allLocalShares.Add(new SharePathEntry(objName.ToString(), objPath.ToString()));
  return allLocalShares;

» Similar Posts

  1. More to know about .NET Timers
  2. How to prevent the configuration file watcher thread in Microsoft Enterprise Library 3.1
  3. User Sample
There are no comments.

Comments are closed