Cool Programming Functionality: Windows Management Instrumentation (Part Two)

As a follow-up to my previous post, here is some sample code in C# which demonstrates how to use Windows Management Instrumentation (WMI) to gather information on a system's logical drives. The code is from a class I am working on (in a personal project, not work related) which will eventually contain several useful functions pertaining to file and drive operations.

Eventually, I would also like the function in this code to return the caption of the device (for example, Memorex 2.4x DVD Writer).

using System;
using System.Management;

namespace AlsFileSystemTools
{
   public enum DriveType
    {
      NoRoot = 1,
      Removable = 2,
      LocalDisk = 3,
      Network = 4,
      CDorDVD = 5,
      RAMDrive = 6
    };

    public struct Drive
    {
      public string Letter;
      public string Description;
      public int       DriveType;
      public string VolumeName;
      public string StatusInfo;
    }

    ///
    /// A collection of functions used to aid in file system    operations
    ///

    public class FileSystemTools
    {
      public FileSystemTools()
      {
      }

      static public Drive[] GetLogicalDrives()
      {

        ManagementClass mgmtDisks = null;
        ManagementObjectCollection mgmtObjCol = null;
        Drive[] Drives = null;

        int i = 0;

        mgmtDisks = new ManagementClass("Win32_LogicalDisk");
        mgmtObjCol = mgmtDisks.GetInstances();

        PropertyDataCollection diskProperties = mgmtDisks.Properties;

        Drives = new Drive[mgmtObjCol.Count];

        foreach(ManagementObject obj in mgmtObjCol)
        {

               Drives[i].Letter = obj["Name"].ToString();
               Drives[i].Description = obj["Description"].ToString();
               Drives[i].DriveType = Convert.ToInt32(obj["DriveType"]);

               if (obj["VolumeName"] != null)
Drives[i].VolumeName = obj["VolumeName"].ToString();

               if (obj["StatusInfo"] != null)
Drives[i].StatusInfo = obj["StatusInfo"].ToString();

               i++;
        }

        mgmtDisks.Dispose();
        mgmtObjCol.Dispose();
        diskProperties = null;
        mgmtDisks = null;
        mgmtObjCol = null;

        return Drives;

      }

    }
}

Comments

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

"$.ajax is not a function" Error When Using jQuery and Darren Johnstone's ASP.NET Upload/Download Module v2