Sunday, July 04, 2004

WMI vs. Win32

Solving performance issues in Win32_LogicalDisk

Off late…. I’ve become a very big fan of WMI… WMI Definitely does wonders and reduces the development time drastically. I was just thinking about how difficult it would be for beginner-intermediate programmers to work on system level, like interacting with h/w, network devices, etc etc… and how error prone those codes are… WMI would definitely reach very far.

But there are many areas that WMI needs to mature or get fixed up. Here is the issue, where I dumped WMI and used Win32 Instead.
Here is the simple WMI code which would list the removable drives of the computer.

# region "WMI Code to retrieve Drives"
ManagementClass driveClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection drives = driveClass.GetInstances();
StringCollection driveCollection = new StringCollection();
foreach (ManagementObject drv in drives)
//Check is made to find whether the drive is from removable storage device
if ((drv["Description"].ToString()=="Removable Disk") && (drv["DriveType"].ToString()=="2"))
# endregion

This code would take a minimum of 4-5 seconds to enumerate my disk drives. And another problem is that, everytime my floppy is also physically checked, which further slows down the execution time. No client would accept this when this feature is used frequently, obviously my client also cribbed and there was no way to solve this issue except to lookout for an Win32 Method, and here is the alternative I wrote…

# region "WIN32 Code to retrieve Drives"
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)]
static extern uint GetDriveType(string lpRootPathName);

/* Retrieves All the Mounted Drives on the computer. */
string[] _drives = System.Environment.GetLogicalDrives();

foreach(string _drive in _drives)
/* Call Win32 GetDriveType to determine the Drive Type, based on the Drive Letter */
_driveTypeLength = GetDriveType(_drive);

//Check whether the passed Drive is a Removable Disk Type
if(_driveTypeLength == 2 || _driveTypeLength == 5)
# endregion

This code would execute in less than 100 MilliSeconds !!! That was an incredible performance boost.

posted by Logu Krishnan : 11:58 AM

Comments: Post a Comment

This page is powered by Blogger. Isn't yours?