如何在C#中检索磁盘信息?
我想使用C#访问计算机上逻辑驱动器的信息。 我该如何做到这一点? 谢谢!
对于大多数信息,您可以使用DriveInfo类。
using System; using System.IO; class Info { public static void Main() { DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { //There are more attributes you can use. //Check the MSDN link for a complete example. Console.WriteLine(drive.Name); if (drive.IsReady) Console.WriteLine(drive.TotalSize); } } }
如何装卷,哪里没有驱动器号?
foreach( ManagementObject volume in new ManagementObjectSearcher("Select * from Win32_Volume" ).Get()) { if( volume["FreeSpace"] != null ) { Console.WriteLine("{0} = {1} out of {2}", volume["Name"], ulong.Parse(volume["FreeSpace"].ToString()).ToString("#,##0"), ulong.Parse(volume["Capacity"].ToString()).ToString("#,##0")); } }
使用System.IO.DriveInfo类http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
如果您想在本地机器上获取单个/特定驱动器的信息。 您可以使用DriveInfo类按如下操作:
//C Drive Path, this is useful when you are about to find a Drive root from a Location Path. string path = "C:\\Windows"; //Find its root directory ie "C:\\" string rootDir = Directory.GetDirectoryRoot(path); //Get all information of Drive ie C DriveInfo driveInfo = new DriveInfo(rootDir); //you can pass Drive path here eg DriveInfo("C:\\") long availableFreeSpace = driveInfo.AvailableFreeSpace; string driveFormat = driveInfo.DriveFormat; string name = driveInfo.Name; long totalSize = driveInfo.TotalSize;
检查DriveInfo类,看它是否包含您需要的所有信息。