C# 获取磁盘空间大小
C# 获取磁盘空间大小方法一:利用System.IO.DriveInfo.GetDrives方法来获取
///
/// 获取指定驱动器的空间总大小(单位为B)
///
/// 只需输入代表驱动器的字母即可 (大写)
///
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;
}
///
/// 获取指定驱动器的剩余空间总大小(单位为B)
///
/// 只需输入代表驱动器的字母即可
///
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;
}
方式二、使用System.Management命名空间下的方法
1、项目首先要添加对 System.Management 的引用
2、新建hardDiskPartition.cs 盘符信息类
///
/// 盘符信息
///
public class HardDiskPartition
{
Data //Data
Properties //Properties
}
3、获取盘符空间信息
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.IO;
namespace ExPortToExcel
{
public partial class Form1 : Form
标签: