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; }
© Copyright 2002-2008, Torsten Rendelmann Page rendered at Thursday, August 21, 2008 4:12:16 PM (W. Europe Standard Time, UTC+01:00)
Like RSS Bandit? Make a donation to help support its development and maintenance. As little as 1€ will help.
SUBSCRIBE RSS GeoURL
newtelligence dasBlog 2.1.8102.813
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.