How can I get the list of logial drives (C#) on a system as well as their capacity and free space?
Is this something new that was added in the latest version of .NET. I wrote a small app to display this years ago but had to go the WMI route at the time. Very handy to know anyway... cheers
Eoin Campbell
2009-04-23 14:18:10
Perfect ... thank you
PaulB
2009-04-23 14:20:53
Quick look on MSDN: was added in .NET 2.0.
Richard
2009-04-23 14:22:19
A:
You can retrieve this information with Windows Management Instrumentation (WMI)
using System.Management;
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
// Loop through each object (disk) retrieved by WMI
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Add the HDD to the list (use the Model field as the item's caption)
Console.WriteLine(moDisk["Model"].ToString());
}
Theres more info here about the attribute you can poll
http://www.geekpedia.com/tutorial233_Getting-Disk-Drive-Information-using-WMI-and-Csharp.html
Eoin Campbell
2009-04-23 14:14:09
+3
A:
Their example has more robust, but here's the crux of it
string[] drives = System.IO.Directory.GetLogicalDrives();
foreach (string str in drives)
{
System.Console.WriteLine(str);
}
You could also P/Invoke and call the win32 function (or use it if you're in unmanaged code).
That only gets a list of the drives however, for information about each one, you would want to use GetDrives as Chris Ballance demonstrates.
Tom Ritter
2009-04-23 14:14:40
+3
A:
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
double fspc = 0.0;
double tspc = 0.0;
double percent = 0.0;
fspc = drive.TotalFreeSpace;
tspc = drive.TotalSize;
percent = (fspc / tspc)*100;
float num = (float)percent;
Console.WriteLine("Drive:{0} With {1} % free", drive.Name,num);
Console.WriteLine("Space Reamining:{0}", drive.AvailableFreeSpace);
Console.WriteLine("Percent Free Space:{0}",percent);
Console.WriteLine("Space used:{0}", drive.TotalSize);
Console.WriteLine("Type: {0}", drive.DriveType);
}
Chris Ballance
2009-04-23 14:16:24