Getting Hard Disk Speed using C# - c#

It is possible to get Hard Disk Information using C#?
Like spin rate in RPM
Model Number
Company Name
Data Transfer Rate
Seek Time
most importantly spin rate.
I have tried with
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive");
properties but it's not giving spin rate.
Please help me?
Dattatrya Moin

Check this : Reading ATAPI SMART Data from Drives using .NET; Temperature Anyone?
using System.Management;
public string GetHDDSerial()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach (ManagementObject wmi_HD in searcher.Get())
{
// get the hardware serial no.
if (wmi_HD["SerialNumber"] != null)
return wmi_HD["SerialNumber"].ToString();
}
return string.Empty;
}

Read this Win32_DiskDrive and try this:
ArrayList hddCollection = new ArrayList();
try
{
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmiObj in searcher.Get)
{
HardDrive hdd = new HardDrive();
hdd.model = wmiObj("Model").ToString;
hdd.type = wmiObj("InterfaceType").ToString;
hddCollection.Add(hdd);
break; // TODO: might not be correct. Was : Exit For
}
}
catch (Exception ex)
{
throw ex;
}

Related

How to get hard drive unique serial number in C#

I develop an activation for a system. to generate request code, I used HDD ID, Bios ID and Processor ID. I used following code to get hard disk ID.
private string getHardDiskID()
{
string hddID = null;
ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject strt in moc)
{
hddID += Convert.ToString(strt["VolumeSerialNumber"]);
}
return hddID.Trim().ToString();
}
But if I plug a removable disk, That ID value is changed. How to get the UNIQUE Serial Number of the hard drive...?
Thanks in advance..
You can try from this source:
As said in the source, a better solution is to get the Hard Drive Serial Number given by the Manufacturer. This value won't change even if you format your Hard Drive.
searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach(ManagementObject wmi_HD in searcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "None";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
++i;
}
ManagementObjectSearcher searcher;
searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
string serial_number="";
foreach (ManagementObject wmi_HD in searcher.Get())
{
serial_number = wmi_HD["SerialNumber"].ToString();
}
MessageBox.Show(serial_number);
Check below code to get HDD Serial
ManagementObjectSearcher objSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
objSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
int i = 0;
foreach(ManagementObject wmi_HD in objSearcher.Get())
{
// get the hard drive from collection
// using index
HardDrive hd = (HardDrive)hdCollection[i];
// get the hardware serial no.
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "None";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
++i;
}
Also You can type "wbemtest" in windows run. WBEMTEST is tool which
helps in running WQL queries.

SoftwareLicensingProduct Which one is my

I need to check whether the OS needs activation,
my following code displays a multitude of "channels".
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher
(
"root\\CIMV2",
"SELECT
Description,
LicenseIsAddon,
LicenseStatus
FROM SoftwareLicensingProduct
WHERE LicenseIsAddon = False"
);
foreach (ManagementObject queryObj in searcher.Get())
{
if (queryObj["Description"].ToString().ToLower().Contains("operating"))
{
foreach (var item in queryObj.Properties)
{
Console.WriteLine(item.Value);
}
}
}
Console.Write("***done***");
Console.ReadLine();
}
How do i know which one to check in order to determine if i need to activate the OS?
Or is my only way to see, if i have any LicenseStatus = 1 in there? Which of course can be wrong if there is one activated and one not activated OS installed.
Thanks
For the time being i filtered the channels a bit more and concluded, that this is good enough:
private void getOSActivation()
{
try
{
ManagementObjectSearcher LicenseSearcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT LicenseStatus,Description FROM SoftwareLicensingProduct");
foreach (ManagementObject LSObj in LicenseSearcher.Get())
{
OStestString = LSObj["Description"].ToString().ToLower();
if (
OStestString.Contains("operating")
&&
// next line is new
(OStestString.Contains("slp") || OStestString.Contains("dm"))
)
{
foreach (var item in LSObj.Properties)
{
OSresults.Add(LSObj["LicenseStatus"].ToString());
}
}
}
}
catch (Exception LSOexception)
{
Console.WriteLine(LSOexception.Message);
}
}

Need to get name (DeviceID) of System Reserved partition

I need to return the DeviceID of the System Reserved partition. I should be able to do this with the Win32_Volume class by first getting the Label property, and if it matches "System Reserved" then get the DeviceID property. The following code crashes with a null reference exception:
static void Main(string[] args)
{
ManagementObjectSearcher ms = new ManagementObjectSearcher("Select * From Win32_Volume");
foreach (ManagementObject mo in ms.Get())
{
if (mo["Label"].ToString() == "System Reserved")
{
Console.WriteLine(mo["DeviceID"].ToString());
}
}
Console.Read();
}
Here it is for anyone that needs to do this:
string sysGuid = "";
try
{
ManagementObjectSearcher ms = new ManagementObjectSearcher("SELECT * FROM Win32_Volume");
foreach (ManagementObject mo in ms.Get())
{
if (mo["Label"].ToString() == "System Reserved")
{
sysGuid = mo["DeviceID"].ToString();
break;
}
}
}
catch (Exception) {}

Find Hard Disk Serial number from Remote SQL Server Installed Hard disk

I have a C#.net Windows form Application with SQL Server. My application use in Multiple user by local Network. Now I need to find Hard disk Serial Number which hard disk installed sql server (Note: By Using C#.net Application Data source ).
How can i find Hard disk Serial number throw by application data source?
This might be useful
using System;
using System.Management;
using System.Collections;
namespace WmiControl
{
public class WMI
{
public bool GetDiskSerial(string Computername)
{
try
{
ManagementScope scope = new ManagementScope(#"\\" + Computername + #"\root\cimv2");
scope.Connect();
ArrayList hdCollection;
ManagementObjectSearcher searcher;
if (GetDiskDrive(scope, out hdCollection, out searcher) || GetDiskSerial(scope, hdCollection, ref searcher))
return true;
else
return false;
}
catch (ManagementException)
{
return false;
}
}
private bool GetDiskSerial(ManagementScope scope, ArrayList hdCollection, ref ManagementObjectSearcher searcher)
{
try
{
ObjectQuery query1 = new ObjectQuery("SELECT * FROM Win32_PhysicalMedia");
searcher = new ManagementObjectSearcher(scope, query1);
int i = 0;
string sDiskSerial = "";
foreach (ManagementObject wmi_HD in searcher.Get())
{
// get the hard drive from collection
// using index
if (i < hdCollection.Count)
{
HardDrive hd = (HardDrive)hdCollection[i];
if (wmi_HD["SerialNumber"] == null)
hd.SerialNo = "";
else
hd.SerialNo = wmi_HD["SerialNumber"].ToString();
}
++i;
}
foreach (HardDrive hd in hdCollection)
{
if (!String.IsNullOrEmpty(hd.SerialNo))
{
sDiskSerial = hd.SerialNo;
break;
}
}
return true;
}
catch (Exception)
{
return false;
}
}
private bool GetDiskDrive(ManagementScope scope, out ArrayList hdCollection, out ManagementObjectSearcher searcher)
{
try
{
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_DiskDrive");
hdCollection = new ArrayList();
searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject wmi_HD in searcher.Get())
{
HardDrive hd = new HardDrive();
hd.Model = wmi_HD["Model"].ToString();
hd.Type = wmi_HD["InterfaceType"].ToString();
hdCollection.Add(hd);
return true;
}
return true;
}
catch (Exception)
{
hdCollection = null;
searcher = null;
return false;
}
}
}
class HardDrive
{
private string model = null;
private string type = null;
private string serialNo = null;
public string Model
{
get { return model; }
set { model = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public string SerialNo
{
get { return serialNo; }
set { serialNo = value; }
}
}
}
See here for more info
You might want also to study CLR
You'll need to resort to WMI. With the proper privileges on the SQL Server machine, you can get the serial number of the hard-drives on it. See here for an example on retrieving the hard-disk's serial number using WMI.
You'll need to figure out which disk holds SQL Server and how to access the SQL Server machine on your own.
You have to do it in 3 stages:
The connection string of the data source gives you the name of the machine on which SQL Server is installed
You must then query the machine to find out the drive which drive SQL Server is installed on
You can then use the code supplied by others here to get the serial number

Wrong calculated CPU usage using C# and WMI

This is my function for enumerating processes on windows box and calculating percentage of CPU usage for each process but results are not correct.
CPU usage does't add up to 100% but more like to 120% or 130% and I don't know what I'm doing wrong.
It seems like it calculats right CPU usage for varoius apps like firefox, VS2010, office,.. but has problems with System Idle Process.
public List<ProcInfo> GetRunningProcesses()
{
List<ProcInfo> allProcesses = new List<ProcInfo>();
UInt64 currentProcessCpuTime = 0;
UInt64 allProcessCpuTime = 0;
SelectQuery wmiQuery = new SelectQuery("SELECT Name, Description, ProcessId, KernelModeTime, UserModeTime FROM Win32_Process");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(connectionScope, wmiQuery);
ManagementObjectCollection moc = oSearcher.Get();
foreach (ManagementObject mo in moc)
{
allProcessCpuTime += (UInt64)mo["KernelModeTime"] + (UInt64)mo["UserModeTime"];
}
foreach (ManagementObject mo in moc)
{
currentProcessCpuTime = (UInt64)mo["KernelModeTime"] + (UInt64)mo["UserModeTime"];
allProcesses.Add(new ProcInfo((string)mo["Name"], (string)mo["Description"], (UInt32)mo["ProcessId"], (currentProcessCpuTime / (double)allProcessCpuTime * 100));
}
return allProcesses;
}
EDIT:
I found that my function is all wrong.
I'm starting a bounty for the best working solution. Solution needs to work for local and remote system and should be fast.
Here is a C# code with performance counters:
public static void DumpProcessesCpu(string machineName)
{
List<PerformanceCounter> counters = new List<PerformanceCounter>();
foreach (Process process in Process.GetProcesses(machineName))
{
PerformanceCounter processorTimeCounter = new PerformanceCounter(
"Process",
"% Processor Time",
process.ProcessName,
machineName);
processorTimeCounter.NextValue();
counters.Add(processorTimeCounter);
}
Thread.Sleep(1000); // 1 second wait, needed to get a sample
foreach (PerformanceCounter processorTimeCounter in counters)
{
Console.WriteLine("Process:{0} CPU% {1}",
processorTimeCounter.InstanceName,
processorTimeCounter.NextValue());
}
}
It's inspired from here: https://learn.microsoft.com/en-us/archive/blogs/bclteam/how-to-read-performance-counters-ryan-byington
You can't really be faster than this, the reason why is explained in the article. Basically, you'll have to read the value twice to get it right, so you need to wait between samples.
However, depending on what you want to do, for example, suppose you want to write a "remote task manager", you can code all this in a background task (thread) and regularly update the values so the end-user will not really see the delay between samples.
var mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfProc_Process");
var run1 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => (ulong)mo.Properties["PercentProcessorTime"].Value);
Thread.Sleep(570); // can be an arbitrary number
var run2 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => (ulong)mo.Properties["PercentProcessorTime"].Value);
var total = run2["_Total"] - run1["_Total"];
foreach (var kvp in run1)
{
var proc = kvp.Key;
var p1 = kvp.Value;
if (run2.ContainsKey(proc))
{
var p2 = run2[proc];
Console.WriteLine("{0}: {1:P}", proc, (double)(p2 - p1) / total);
}
}
Here is a C# block of code tested and validated and thanks to fejesjoco, I used his code and made the test to get it to work.
public class CPUUtilizationTests
{
[Test]
public void TestPercentProcessorTime()
{
Assert.That(PercentProcessorTime("Idle"), Is.Not.GreaterThan(100.0));
}
public float PercentProcessorTime(string processName)
{
var mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfProc_Process");
var run1 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => mo);
System.Threading.Thread.Sleep(1000); // can be an arbitrary number
var run2 = mos.Get().Cast<ManagementObject>().ToDictionary(mo => mo.Properties["Name"].Value, mo => mo);
if (!run2.ContainsKey(processName)) throw new Exception(string.Format("Process not found: {0}", processName));
string percentageProcessorTime = "PercentProcessorTime";
string total = "_Total";
ulong percentageDiff = (ulong)run2[processName][percentageProcessorTime] - (ulong)run1[processName][percentageProcessorTime];
ulong totalDiff = (ulong)run2[total][percentageProcessorTime] - (ulong)run1[total][percentageProcessorTime];
return ((float)percentageDiff / (float)totalDiff)*100.0f;
}
}

Categories

Resources