How do I retrieve disk information in C#?

烂漫一生 提交于 2019-11-26 07:37:56

问题


I would like to access information on the logical drives on my computer using C#. How should I accomplish this? Thanks!


回答1:


For most information, you can use the DriveInfo class.

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);
        }
    }
}



回答2:


If you want to get information for single/specific drive at your local machine. You can do it as follow using DriveInfo class:

//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 i.e "C:\\"
string rootDir = Directory.GetDirectoryRoot(path);

//Get all information of Drive i.e C
DriveInfo driveInfo = new DriveInfo(rootDir); //you can pass Drive path here e.g   DriveInfo("C:\\")

long availableFreeSpace = driveInfo.AvailableFreeSpace;
string driveFormat = driveInfo.DriveFormat;
string name = driveInfo.Name;
long totalSize = driveInfo.TotalSize;



回答3:


Use System.IO.DriveInfo class http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx




回答4:


What about mounted volumes, where you have no drive letter?

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"));
  }
}



回答5:


Check the DriveInfo Class and see if it contains all the info that you need.



来源:https://stackoverflow.com/questions/412632/how-do-i-retrieve-disk-information-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!