Getting a list of logical drives
60,382
Solution 1
System.IO.DriveInfo.GetDrives()
Solution 2
foreach (var drive in DriveInfo.GetDrives())
{
double freeSpace = drive.TotalFreeSpace;
double totalSpace = drive.TotalSize;
double percentFree = (freeSpace / totalSpace) * 100;
float num = (float)percentFree;
Console.WriteLine("Drive:{0} With {1} % free", drive.Name, num);
Console.WriteLine("Space Remaining:{0}", drive.AvailableFreeSpace);
Console.WriteLine("Percent Free Space:{0}", percentFree);
Console.WriteLine("Space used:{0}", drive.TotalSize);
Console.WriteLine("Type: {0}", drive.DriveType);
}
Solution 3
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.
Solution 4
maybe this is what you want:
listBox1.Items.Clear();
foreach (DriveInfo f in DriveInfo.GetDrives())
listBox1.Items.Add(f);
Solution 5
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
Comments
-
PaulB over 3 years
How can I get the list of logial drives (C#) on a system as well as their capacity and free space?
-
Eoin Campbell about 15 yearsIs 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
-
Richard about 15 yearsQuick look on MSDN: was added in .NET 2.0.
-
Darrel Lee almost 8 yearsYou might also want to check the IsReady property
-
Sheo Narayan almost 8 yearsCan't get this working on my computer. System.Management doesn't have ManagementObjectSearcher class now. The URL is also not pointing to a valid web page.
-
Gippeumi over 7 yearsYou need to add reference for that. On Visual Studio, Right click on project then go to Add -> Reference. Then, search for "System.Management" and add it.