How can I check for available disk space? - c#

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

Related

C#: how to collect service only for certain process name by using ServiceController.GetServices()

I am able to get all the process using Process.GetProcesses() under "System.Diagnostics" namespace.
Is there any way to get all the service name within certain process by using "ServiceController.GetServices()"?
foreach (var theProcess in Process.GetProcesses())
{
if(theProcess.ProcessName.ToUpper() == "SVCHOST")
{
ServiceController.GetServices().Where(e=>e.)
}
//Console.WriteLine("Process: {0} ID: {1}", theProcess.ProcessName, theProcess.Id);
}
No, there is no way because you have no special attributes or properties. But you can do the same thing using ManagementObjectSearcher
foreach (var theProcess in Process.GetProcesses())
{
if (theProcess.ProcessName.ToUpper() == "SVCHOST")
{
ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", string.Format("SELECT * FROM Win32_Service " + "where ProcessId={0}", theProcess.Id));
foreach (ManagementObject mo in mos.Get())
{
Console.WriteLine("Name: " + mo["Name"]);
}
}
}

Saving ManagementObject query as double

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"];

Where can I get info about notebook's model name?

I trying to get info about HW from notebooks. I do this via WMI, but not always there contains the info about notebook model for example. It depends on the manufacturer, SONY never contains HW info in WMI.
FileStream fs = new FileStream(#"C:\log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
string[] Names = { "Win32_Fan", "Win32_HeatPipe", "Win32_Refrigeration", "Win32_TemperatureProbe", "Win32_Keyboard", "Win32_PointingDevice",
"Win32_AutochkSetting", "Win32_CDROMDrive" , "Win32_DiskDrive" ,"Win32_FloppyDrive", "Win32_PhysicalMedia","Win32_TapeDrive" ,
"Win32_1394Controller","Win32_1394ControllerDevice", "Win32_AllocatedResource", "Win32_AssociatedProcessorMemory","Win32_BaseBoard",
"Win32_BIOS", "Win32_Bus","Win32_CacheMemory","Win32_ControllerHasHub","Win32_DeviceBus","Win32_DeviceMemoryAddress", "Win32_DeviceSettings",
"Win32_DMAChannel","Win32_FloppyController","Win32_IDEController","Win32_IDEControllerDevice","Win32_InfraredDevice","Win32_IRQResource","Win32_MemoryArray",
"Win32_MemoryArrayLocation","Win32_MemoryDevice","Win32_MemoryDeviceArray","Win32_MemoryDeviceLocation","Win32_MotherboardDevice","Win32_OnBoardDevice",
"Win32_ParallelPort","Win32_PCMCIAController","Win32_PhysicalMemory","Win32_PhysicalMemoryArray","Win32_PhysicalMemoryLocation","Win32_PNPAllocatedResource",
"Win32_PNPDevice","Win32_PNPEntity","Win32_PortConnector","Win32_PortResource","Win32_Processor","Win32_SCSIController", "Win32_SCSIControllerDevice","Win32_SerialPort",
"Win32_SerialPortConfiguration","Win32_SerialPortSetting","Win32_SMBIOSMemory","Win32_SoundDevice","Win32_SystemBIOS","Win32_SystemDriverPNPEntity","Win32_SystemEnclosure",
"Win32_SystemMemoryResource","Win32_SystemSlot","Win32_USBController","Win32_USBControllerDevice","Win32_USBHub","Win32_NetworkAdapter",
"Win32_NetworkAdapterConfiguration","Win32_NetworkAdapterSetting","Win32_Battery","Win32_CurrentProbe","Win32_PortableBattery",
"Win32_PowerManagementEvent","Win32_VoltageProbe","Win32_DriverForDevice","Win32_Printer","Win32_PrinterConfiguration","Win32_PrinterController",
"Win32_PrinterDriver","Win32_PrinterDriverDll","Win32_PrinterSetting","Win32_PrintJob","Win32_TCPIPPrinterPort","Win32_POTSModem","Win32_POTSModemToSerialPort",
"Win32_DesktopMonitor","Win32_DisplayConfiguration","Win32_DisplayControllerConfiguration","Win32_VideoConfiguration","Win32_VideoController","Win32_VideoSettings"};
foreach (string name in Names)
{
sw.WriteLine(" ");
sw.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
sw.WriteLine(name);
sw.WriteLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " + name);
ManagementObjectCollection information = searcher.Get();
foreach (ManagementObject obj in information)
{
foreach (PropertyData data in obj.Properties)
{
sw.WriteLine("{0} = {1}", data.Name, data.Value);
}
}
}
sw.Close();
Where can I get this info?
Thanks!
You could try getting this information from the BIOS information, which is stored in the registry under the HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS. It should be in the SystemProductName or SystemVersion value.
Model and serial number contain in the "Win32_ComputerSystemProduct".

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 to search for a file on a remote system by file name using WMI in C#?

How do I search for a file on a remote system by it's filename using WMI and C#?
Try this code and check this.
Download also WMI Code Creator ( check on google because I can't link it due to my reputation <10) to easily test your WMI query.
using System;
using System.Management;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ConnectionOptions oConn = new ConnectionOptions();
oConn.Impersonation = ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
string[] arrComputers = "clientName"};
foreach (string strComputer in arrComputers)
{
Console.WriteLine("==========================================");
Console.WriteLine("Computer: " + strComputer);
Console.WriteLine("==========================================");
ManagementObjectSearcher searcher = new ManagementObjectSearcher
(
new ManagementScope("\\\\" + strComputer + "\\root\\CIMV2", oConn),
new ObjectQuery( #"SELECT * FROM CIM_DataFile WHERE Name = 'WhatyouWant.ToSearch'")
);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("CIM_DataFile instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Path: {0}", queryObj["Path"]);
}
}
}
catch(ManagementException err)
{
MessageBox.Show("An error occurred while querying for WMI data: " + err.Message);
}
}
}
}

Categories