How to evaluate all LogicalDisk instances in a machine excluding mapped network drives?

38 Views Asked by At

I am writing a method to get the physical hardware serial number of the operating system drive. I am using the call

ManagementClass("Win32_LogicalDisk").GetInstances()

to get all drive instances in my machine. I am only interested in local, physically attached drives, specifically C:, however disconnected network drives are massively slowing the call down (up to a minute or two waiting on drives to fail to resolve).

In completeness, the method is scanning all LogicalDisk instances, correlating C: firstly using the LogicalDiskToPartition mapper, and secondly the DiskDriveToDiskParition mapper, to find the DiskDrive hosting the operating system1. Finally having the system's disk drive, I am gathering the SerialNumber of the disk (the ultimate objective of the method).

The method works perfectly in Windows however it is laborious if I can't eliminate network drives. I would welcome suggestions of faster ways of achieving my end goal, as well as how to make the method operating system agnostic (iOS, Linux, Android etc.)

1 If the operating system is not on C: then I would also welcome knowing how to generally identify the 'system' drive.

1

There are 1 best solutions below

1
jason.kaisersmith On

A quick way to find out where Windows is installed is simply to use the Special folder System

var systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);    
Console.WriteLine($"System Path  = {systemPath }");

This will output something like:

System Path = C:\WINDOWS\system32

So you can retrieve the disk from the first letter

You can also do this to retrieve drive information. I believe it works on Windows & Linux, although I haven't tried it.

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)            
    Console.WriteLine($"Name = {d.Name}; Type = {d.DriveType} format = {d.DriveFormat} Label = {d.VolumeLabel} Root = {d.RootDirectory} IsReady = {d.IsReady}");