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?
Alternatively referred to as disk space, disk storage, or storage capacity, disk capacity is the maximum amount of data a disc, disk, or drive is capable holding. Disk capacity is displayed in MB (megabytes), GB (gigabytes), or TB (terabytes).
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With