3

I'm using the following code to get my drive serial number. It's working fine with Windows 7, 8, 8.1, and 10 Professional, but I'm getting an error on Windows 10 Home.

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in searcher.Get())
{
     if (wmi_HD["SerialNumber"] == null)
          hddId = null;
     else
          hddId = wmi_HD["SerialNumber"].ToString();
}

I'm getting

System.NullReferenceException : Object reference not set to an instance of an object.

Does anyone know why? What do I need to do to get the serial number in this case?

One more question: if I boot the OS from my pendrive, will this code work? How could I know that the OS is running from a pendrive or disk or any other resource?

When I go to the Device Manager, I see this:

enter image description here

Pranav Patel
  • 1,541
  • 14
  • 28

2 Answers2

5

I am adding this as an answer because it can save lot of time while debugging scenarios like System.NullReferenceException in WMI.

  1. Windows+R (run command)
  2. Type wbemtest

And connect to the machine for which you want to fetch information. Fire the query for Win32_DiskDrive and check the output for properties that you can fetch.

Amit Shakya
  • 1,396
  • 12
  • 27
0

This is what I'm using on Windows 10 v1809:

using System;
using System.Management;

namespace GetSerialNo
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

            foreach (ManagementObject info in searcher.Get())
            {
                Console.WriteLine("DeviceID: " + info["DeviceID"].ToString());
                Console.WriteLine("Model: " + "Model: " + info["Model"].ToString());
                Console.WriteLine("Interface: " + "Interface: " + info["InterfaceType"].ToString());
                Console.WriteLine("Serial#: " + "Serial#: " + info["SerialNumber"].ToString());
            }

            Console.ReadLine();
        }
    }
}

For details please see http://csharphelper.com/blog/2017/10/get-hard-drive-serial-number-c/

For the associated link Get Hard disk serial Number given by @ADreNaLiNe-DJ I wasn't able to find the required assembly reference for HardDrive hd = new HardDrive();

user8128167
  • 6,929
  • 6
  • 66
  • 79