Unable to get system hard drive SerialNumber using Win32_DiskDrive - c#

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:

I am adding this as an answer because it can save lot of time while debugging scenarios like System.NullReferenceException in WMI.
Windows+R (run command)
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.

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();

Related

Get VID/ PID of printer using C# with unknown device id

I have a usb printer. I don't know how to take device id also. I want to take vid/ pid using c# code. Any help appreciated.
Have you tried:
using System.Management;
ManagementObjectSearcher myPrinterObject = new ManagementObjectSearcher("select * from Win32_Printer");
foreach (ManagementObject obj in myPrinterObject.Get())
{
Console.WriteLine("Name - " + obj["Name"]);
Console.WriteLine("Network - " + obj["Network"]);
Console.WriteLine("Availability - " + obj["Availability"]);
Console.WriteLine("Is default printer - " + obj["Default"]);
Console.WriteLine("DeviceID - " + obj["DeviceID"]);
Console.WriteLine("Status - " + obj["Status"]);
Console.WriteLine(String.Empty.PadLeft(obj["Name"].ToString().Length, '='));
}
The WMI properties are:
https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printer?redirectedfrom=MSDN
You can also wrap the manufacturer DLL with a C++ wrapper and then call that from your C# application seamlessly however this will could take you a long time to write!

Get driver file version in windows

How can I get file attributes or version info of driver file in windows via c#.
I'm using this code:
var version = File.GetAttributes(Environment.SystemDirectory + #"\drivers\acpi.sys");
but this code throw exception: Could not find file 'C:\Windows\system32\drivers\acpi.sys'..
Then i'm using this code var dir = Directory.GetFiles(Environment.SystemDirectory + #"\drivers"); in dir variable i have 4 files. If I open this folder via windows explorer i have in folder 300+ files. What am I doing wrong?
You should using >= FrameWork .net 4,
add :
using System.Management;
and add the reference System.Management;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPSignedDriver");
ManagementObjectCollection moc = searcher.Get();
foreach (var manObj in moc)
{
Console.WriteLine("Device Name:" + manObj["FriendlyName"] + " \r\nDeviceID: " + manObj["DeviceID"] + "\r\nDriverDate: " + manObj["DriverDate"] + "\r\nDriverVersion: " + manObj["DriverVersion"] + "\r\nDriverName:" + manObj["DriverName"] +"\n\r======================================\n\n";);
}
Result (part):
Another way could be reading the version from the file directly. Should work for 64/32bit apps, but I am not sure if you can get to all files.
string directory;
if (Environment.Is64BitOperatingSystem)
directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative");
else
directory = Environment.GetFolderPath(Environment.SpecialFolder.System);
var info = FileVersionInfo.GetVersionInfo(Path.Combine(directory, "drivers", "acpi.sys"));
You can find more information about Sysnative folders at Folders under C:\Windows\System32\GroupPolicyUsers created with Directory or File System Redirector

Why "root\\StandardCimv2" in Windows 7 doesn't work?

workWhen i try show list with adapters name in combobox like this:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\StandardCimv2","SELECT * FROM MSFT_NetAdapter");
foreach (ManagementObject queryObj in searcher.Get())
{
try
{
comboBox1.Items.Add(queryObj["Name"].ToString());
}
catch (Exception)
{
comboBox1.Items.Add("");
}
}
All good...because used Windows 8. If i run app on PC with Windows 7 i get error:
System.Management.ManagementException: Invalid namespace
Later I noticed one thing...if this line code:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\StandardCimv2","SELECT * FROM MSFT_NetAdapter")
Replace on this:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapter");
The error disappears and everything works. And now Question!
Why this "root\StandardCimv2" not work in Win7? But with this "root\CIMV2" all good.
Thanks in advance.
The Win32_NetworkAdapter class works on Vista and 7.
This answer has an example of using it (in PowerShell) to retrieve Name and connection Speed:
https://stackoverflow.com/a/3002568/550712
It looks like it also has the "Name" property so it might work as a direct replacement in your code.

Programmatically I need to disconnect my internet connection using C#?

I'm using my broadband internet through Wan Miniport (PPPOE) connection and I've Windows 7 as my OS. I would like to disconnect the internet connection through C#. I searched a lot over the internet but I'm not sure which methodology (WMI, WinInet etc) suits my connection.
I will be reconnecting through another software later, hence my requirement is just to disconnect from the internet rather totally disabling it permanently.
Kindly please give some solution & code to implement this.
?
Use WMI:
C#:
var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
"WHERE NetConnectionId != null " +
"AND Manufacturer != 'Microsoft' ");
using (var searcher = new ManagementObjectSearcher(wmiQuery))
{
foreach (ManagementObject item in searcher.Get())
{
if (((String)item["NetConnectionId"]) == "Local Area Connection")
{
using (item)
{
item.InvokeMethod("Disable", null);
}
}
}
}
VB:
Dim wmiQuery = New SelectQuery("SELECT * FROM Win32_NetworkAdapter " & "WHERE NetConnectionId != null " & "AND Manufacturer != 'Microsoft' ")
Using searcher = New ManagementObjectSearcher(wmiQuery)
For Each item As ManagementObject In searcher.[Get]()
If DirectCast(item("NetConnectionId"), [String]) = "Local Area Connection" Then
Using item
item.InvokeMethod("Disable", Nothing)
End Using
End If
Next
End Using

Get PC's Monitor Information Using .NET / WMI

Is there anyway using WMI/.Net to grab monitor information such as Manufacturer, Serial Number, Monitor Size etc.?
Using a script is an option as well, or can I query the registry directly to get this information?
SELECT * FROM Win32_DesktopMonitor doesn't really return any useful information for me in this case.
Hey, I use this tool for a lot of my WMI work, especially when prototyping and creating POCs....
Microsoft WMI Code Generator
This tool is great for creating quick console app code for any wmi query or method invocation in both C# and VB.NET
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_DesktopMonitor");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_DesktopMonitor instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Description: {0}", queryObj["Description"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
The code above will get you the make and model of the monitor.
You may want to try this
https://raw.githubusercontent.com/MaxAnderson95/Get-Monitor-Information/master/Get-Monitor.ps1
Cheers
That select query should give you what you want. Here is the documentation which contains the details of the query.
Then you could do something like this:
public void GetMonitorDetails()
{
using(ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DesktopMonitor")
{
foreach(ManagementObject currentObj in searcher.Get())
{
String name = currentObj("Name").ToString();
String device_id = currentObj("DeviceID").ToString();
// ...
}
}
}
This post, combined with the answer below about the WMI management tool had my answer. Here is the code that returns your monitor resolutions.
try {
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM WmiMonitorBasicDisplayParams");
foreach (ManagementObject queryObj in searcher.Get()) {
Debug.WriteLine("-----------------------------------");
Debug.WriteLine("WmiMonitorBasicDisplayParams instance");
Debug.WriteLine("-----------------------------------");
Debug.WriteLine("Description: {0}", queryObj["SupportedDisplayFeatures"]);
}
} catch (ManagementException e) {
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
In my case, I'm still stuck, because it is returning the "scaled down" resolution of each monitor. One of mine is a 4K display, being reported as 2560x1440.

Categories

Resources