torsten's .NET blog In the end, everything is a gag [Ch. Chaplin]
# Friday, October 19, 2007
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:

/// <summary>
/// Container for Share entries
/// </summary>
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<SharePathEntry> GetLocalShares()
{
  List<SharePathEntry> allLocalShares = new List<SharePathEntry>(); // 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;
}
Technorati tags:  |  | 
Friday, October 19, 2007 11:02:12 AM (W. Europe Daylight Time, UTC+02:00)    #  Comments [0]  | 
Navigation

Like RSS Bandit? Make a donation to help support its development and maintenance. As little as 1€ will help.

Make payments with PayPal - it's fast, free and secure!
On this page....
<October 2007>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

SUBSCRIBE RSS GeoURL e-mail

Search
Categories
Blogroll

newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Join WebHost4Life.com