C# 获取磁盘的空间大小
private void button1_Click(object sender, EventArgs e)
{
string strRecordFilePath = "d:/dasda";
string str=strRecordFilePath.Substring(0, 1).ToUpper();//取首字母并转为大写
this.m_ChkDisk(str);
}
//strDisk应为大写,如 "D"
private void m_ChkDisk(string strDisk)
{
if (strDisk == "")
return;
txtTotal.Text = GetHardDiskSpace(strDisk).ToString();
txtFreeSpace.Text = GetHardDiskFreeSpace(strDisk).ToString();
int a, b, c;
a = Convert.ToInt32(txtTotal.Text);
b = Convert.ToInt32(txtFreeSpace.Text);
c = a - b;
txtUse.Text=c.ToString();
}
/// <summary>
/// 获取指定驱动器的空间总大小(单位为B)
/// </summary>
/// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 (大写)</param>
/// <returns> </returns>
public static long GetHardDiskSpace(string str_HardDiskName)
{
long totalSize= new long();
str_HardDiskName=str_HardDiskName +":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
totalSize = drive.TotalSize / (1024 * 1024 * 1024);
}
}
return totalSize;
}
/// <summary>
/// 获取指定驱动器的剩余空间总大小(单位为B)
/// </summary>
/// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param>
/// <returns> </returns>
public static long GetHardDiskFreeSpace(string str_HardDiskName)
{
long freeSpace = new long();
str_HardDiskName = str_HardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
freeSpace = drive.TotalFreeSpace / (1024 * 1024 * 1024);
}
}
return freeSpace;
}