Saving ManagementObject query as double - c#

I'm currently making a program the monitors the uptime and size of servers on a network. I've run into some problems with displaying the size of the servers and what space is left.
My code is
public void setSpace(string ip)
{
ManagementScope scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2");
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
SelectQuery query1 = new SelectQuery("Select * from Win32_LogicalDisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
ManagementObjectCollection queryCollection1 = searcher1.Get();
foreach (ManagementObject m in queryCollection)
{
// Display the remote computer information
Console.WriteLine("Computer Name : {0}",
m["csname"]);
Console.WriteLine("Windows Directory : {0}",
m["WindowsDirectory"]);
Console.WriteLine("Operating System: {0}",
m["Caption"]);
Console.WriteLine("Version: {0}", m["Version"]);
Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]);
Console.WriteLine();
}
foreach (ManagementObject mo in queryCollection1)
{
Console.WriteLine(" Disk Name : {0}", mo["Name"]);
Console.WriteLine(" Disk Size : {0}", mo["Size"]);
Console.WriteLine(" FreeSpace : {0}", mo["FreeSpace"]);
Console.WriteLine(" Disk DeviceID : {0}", mo["DeviceID"]);
Console.WriteLine(" Disk VolumeName : {0}", mo["VolumeName"]);
Console.WriteLine(" Disk SystemName : {0}", mo["SystemName"]);
Console.WriteLine("Disk VolumeSerialNumber : {0}", mo["VolumeSerialNumber"]);
Console.WriteLine();
freeSpace = freeSpace + (double)mo["FreeSpace"];
totalSpace = totalSpace + (double)mo["Size"];
}
Console.ReadLine();
}
I'm trying to take the FreeSpace and Size numbers and put them in a double variable.
freeSpace = freeSpace + (double)mo["FreeSpace"];
totalSpace = totalSpace + (double)mo["Size"];
When I try to run the program I get an exception.
'Object reference not set to an instance of an object.'

You got a NullReferenceException because the code doesn't return a specified member (eg. FreeSpace). I tried the code in my PC where I have 2 partitions and 1 DVD drive. Exception was raised when it reached the DVD drive (empty disk) while it was iterating the queryCollection1 object. So you must check if the member of mo object you want is a null reference.
if (mo["FreeSpace"] != null)
freeSpace = freeSpace + (ulong)mo["FreeSpace"];
if (mo["Size"] != null)
totalSpace = totalSpace + (ulong)mo["Size"];
I also change the cast to ulong because FreeSpace and Size are ulong type. And there's an implicit conversion from ulong to double. You don't need to change the variable type of freeSpace and totalSpace.

Your casts are wrong. Instead of cast to double, you should cast to ulong. The variables freeSpace and totalSpace should be of the same type and initialized before the first use.
freeSpace = freeSpace + (ulong)mo["FreeSpace"];
totalSpace = totalSpace + (ulong)mo["Size"];

Related

foreach (ManagementObject user in users) doesn't seem to be retrieving all local accounts

I use the following method to get all LOCAL user accounts on a machine. It finds 12 of them, but only processes the first one.
ObjectQuery wql = new ObjectQuery(#"SELECT * FROM Win32_UserProfile");
ManagementObjectSearcher usersSearcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection users = usersSearcher.Get();
Console.WriteLine("Users: " + "[" + users.Count + "]"); // Reports 12
foreach (ManagementObject user in users)
{
Console.WriteLine("Checking User: " + GetNameFromSID(user["SID"].ToString()));
}
It seems that it used to report all accounts. Is there a surefire way to get this information?

how to format drive with 32KB cluster

I am not a C# programer but I need to format drive with 32KB cluster using C#. I found "Format method of the Win32_Volume class" but when I am trying to format drive I always get an error 15 (Cluster size is too small). This is my code:
public static int DriveFormatting(string driveLetter)
{
string FileSystem = "FAT32", Label = "";
Boolean QuickFormat = true, EnableCompression = false;
UInt32 ClusterSize = 32;
int result = -1;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume WHERE DriveLetter = '"+ driveLetter +"'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach(ManagementObject management in searcher.Get())
{
Console.WriteLine("Formating disk " + driveLetter + "...");
result = Convert.ToInt32(management.InvokeMethod("Format", new object[] { FileSystem, QuickFormat, ClusterSize, Label, EnableCompression }));
}
return result;
}
How can I do this? Thanks in advance.

C# Collect IOps PErformance Data RealTime?

I am trying to build a small Software App which can collect Performance Data from a Windows Machine.
Here is a part of the code i use and PrintScreen which gives me not a right number.
Please Tell me what is wrong in my Code and why is the scale not right in the code.(The default scale is 1)
PrintScreen:
http://postimage.org/image/6za0g7e4t/
ManagementScope oMs = new System.Management.ManagementScope("root\\cimv2");
//Inventory
ObjectQuery InventQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher Inventsearcher = new ManagementObjectSearcher(oMs, InventQuery);
ManagementObjectCollection InventCollection = Inventsearcher.Get();
foreach (ManagementObject mgt in InventCollection)
{
outBox.AppendText(mgt["csname"].ToString() + "\n");
}
//Performance
//ObjectQuery PerfQuery = new ObjectQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk");
ObjectQuery PerfQuery = new ObjectQuery("SELECT * FROM Win32_PerfRawData_PerfDisk_LogicalDisk");
ManagementObjectSearcher Perfsearcher = new ManagementObjectSearcher(oMs, PerfQuery);
ManagementObjectCollection PerfCollection = Perfsearcher.Get();
foreach (ManagementObject mgt in PerfCollection)
{
mgt.SetPropertyQualifierValue("DiskWritesPerSec", "DefaultScale", ScaleBox.Text);
mgt.SetPropertyQualifierValue("DiskReadsPerSec", "DefaultScale", ScaleBox.Text);
outBox.AppendText("Write IOps: " + mgt["Name"].ToString() + " ");
outBox.AppendText("Write IOps: " + mgt["DiskWritesPerSec"].ToString() + " ");
outBox.AppendText("Read IOps: " + mgt["DiskReadsPerSec"].ToString() + "\n");
}

How to detect freespace and disk information from one server to other in C#

If there are 3 pcs on network and if I want to detect the freespace and disk details of one pc from another pc then how to go about it...
I have found this code. but I don't know how should I test it inorder to know whether it is working.
is this the right way?
public Hashtable ReadFreeSpaceOnNetworkDrives()
{
//create Hashtable instance to hold our info
Hashtable driveInfo = new Hashtable();
//query the win32_logicaldisk for type 4 (Network drive)
SelectQuery query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=4");
//execute the query using WMI
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
//loop through each drive found
foreach (ManagementObject drive in searcher.Get())
{
//add the name & freespace to our hashtable
driveInfo.Add("Drive", drive["name"]);
driveInfo.Add("Space", drive["FreeSpace"]);
}
return driveInfo;
}
Update:
I got the answer to my question but I have got the code but it is in console application and I want in windows form application with a graphical representation of the disk space and drive info. How can I use this code and go about doing that?
ManagementScope scope = new ManagementScope("\\\\10.74.160.126\\root\\cimv2");
scope.Connect();
ObjectQuery query = new ObjectQuery( "SELECT * FROM Win32_OperatingSystem");
SelectQuery query1 = new SelectQuery("Select * from Win32_LogicalDisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
ManagementObjectCollection queryCollection1 = searcher1.Get();
foreach (ManagementObject m in queryCollection)
{
// Display the remote computer information
Console.WriteLine("Computer Name : {0}",
m["csname"]);
Console.WriteLine("Windows Directory : {0}",
m["WindowsDirectory"]);
Console.WriteLine("Operating System: {0}",
m["Caption"]);
Console.WriteLine("Version: {0}", m["Version"]);
Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]);
Console.WriteLine();
}
foreach (ManagementObject mo in queryCollection1)
{
Console.WriteLine(" Disk Name : {0}", mo["Name"]);
Console.WriteLine(" Disk Size : {0}", mo["Size"]);
Console.WriteLine(" FreeSpace : {0}", mo["FreeSpace"]);
Console.WriteLine(" Disk DeviceID : {0}", mo["DeviceID"]);
Console.WriteLine(" Disk VolumeName : {0}", mo["VolumeName"]);
Console.WriteLine(" Disk SystemName : {0}", mo["SystemName"]);
Console.WriteLine("Disk VolumeSerialNumber : {0}", mo["VolumeSerialNumber"]);
Console.WriteLine();
}
Console.ReadLine();
}
The code checks all the drives on the pc where you run this program. It returns a table with 2 entries per drive. One with the name and one with the free space. You can just write a simple program that uses this method and displays this data. It should be possible to query the drives from a remote computer. Maybe this article can tell you more http://msdn.microsoft.com/en-us/library/ms257337%28v=vs.80%29.aspx
EDIT:
public Hashtable ReadFreeSpaceOnNetworkDrives(String FullComputerName)
{
ManagementScope scope = new ManagementScope(fullComputerName);
scope.Connect();
//create Hashtable instance to hold our info
Hashtable driveInfo = new Hashtable();
//query the win32_logicaldisk for type 4 (Network drive)
SelectQuery query = new SelectQuery("select name, FreeSpace from win32_logicaldisk where drivetype=4");
//execute the query using WMI
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope,query);
//loop through each drive found
foreach (ManagementObject drive in searcher.Get())
{
//add the name & freespace to our hashtable
driveInfo.Add("Drive", drive["name"]);
driveInfo.Add("Space", drive["FreeSpace"]);
}
return driveInfo;
}
covert into c#. and that may help you. http://www.codeguru.com/forum/showthread.php?t=426869

How can I check for available disk space?

I need a way to check available disk space on a remote Windows server before copying files to that server. Using this method I can check to see if the primary server is full and if it is, then I'll copy the files to a secondary server.
How can I check for available disk space using C#/ASP.net 2.0?
You can check it by doing the following:
Add the System.Management.dll as a reference to your project.
Use the following code to get the diskspace:
using System;
using System.Management;
public string GetFreeSpace();
{
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
string freespace = disk["FreeSpace"];
return freespace;
}
There are a myriad of ways to do it, I'd check the System.Management namespace for more ways.
Here's one such way from that page:
public void GetDiskspace()
{
ConnectionOptions options = new ConnectionOptions();
ManagementScope scope = new ManagementScope("\\\\localhost\\root\\cimv2",
options);
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
SelectQuery query1 = new SelectQuery("Select * from Win32_LogicalDisk");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope, query1);
ManagementObjectCollection queryCollection1 = searcher1.Get();
foreach (ManagementObject m in queryCollection)
{
// Display the remote computer information
Console.WriteLine("Computer Name : {0}", m["csname"]);
Console.WriteLine("Windows Directory : {0}", m["WindowsDirectory"]);
Console.WriteLine("Operating System: {0}", m["Caption"]);
Console.WriteLine("Version: {0}", m["Version"]);
Console.WriteLine("Manufacturer : {0}", m["Manufacturer"]);
Console.WriteLine();
}
foreach (ManagementObject mo in queryCollection1)
{
// Display Logical Disks information
Console.WriteLine(" Disk Name : {0}", mo["Name"]);
Console.WriteLine(" Disk Size : {0}", mo["Size"]);
Console.WriteLine(" FreeSpace : {0}", mo["FreeSpace"]);
Console.WriteLine(" Disk DeviceID : {0}", mo["DeviceID"]);
Console.WriteLine(" Disk VolumeName : {0}", mo["VolumeName"]);
Console.WriteLine(" Disk SystemName : {0}", mo["SystemName"]);
Console.WriteLine("Disk VolumeSerialNumber : {0}", mo["VolumeSerialNumber"]);
Console.WriteLine();
}
string line;
line = Console.ReadLine();
}
by using this code
static void Main()
{
try
{
DriveInfo driveInfo = new DriveInfo(#"C:");
long FreeSpace = driveInfo.AvailableFreeSpace;
}
catch (System.IO.IOException errorMesage)
{
Console.WriteLine(errorMesage);
}
}
IF you are getting the error 'The device is not ready' .i.e your device is not ready .
If you are trying this code for a CD drive without CD you will get the same error : )
This seems to be an option from the System.IO:
DriveInfo c = new DriveInfo("C");
long cAvailableSpace = c.AvailableFreeSpace;
You can use the DriveInfo class
DriveInfo[] oDrvs = DriveInfo.GetDrives();
foreach (var Drv in oDrvs) {
if (Drv.IsReady) {
Console.WriteLine(Drv.Name + " " + Drv.AvailableFreeSpace.ToString);
}
}
You can use WMI, see this related question:
Best way to query disk space on remote server

Categories