C#下 获取硬盘容量
C#下,怎么获取硬盘容量.
我要知道某盘下还剩余多少空间,以确定当前的这些文件能不能拷贝到该盘下.
好象GetDiskFreeSpace()可以,可不知道怎么用
请高手们指点,谢谢!
------解决方案--------------------1 查查有没有类似的api
2 可获得总容量 使用directory类递归计算已被使用的容量 ,相减
我觉得肯定有api 或现成的方法
------解决方案--------------------[DllImport( "kernel32 ", CharSet=CharSet.Auto,
SetLastError = true) ]
static extern bool GetDiskFreeSpace(
string strRoot, out uint sectersPerCluster,
out uint bytesPerSector,
out uint numFreeClusters, out uint totalClusters);
------解决方案--------------------[DllImport( "KERNEL32.DLL ", EntryPoint= "GetDiskFreeSpaceExW ", CharSet=CharSet.Unicode)]
public static extern bool GetDiskFreeSpace(string drive,ref long freeBytes, ref long totalBytes, ref long totalFreeBytes);
------解决方案--------------------GetDisk(string dri)
==> 10.55GB
private static string GetDisk(string dri)
{
try
{
ManagementObject obj2 = new ManagementObject( "win32_logicaldisk.deviceid=\ " " + dri + ":\ " ");
obj2.Get();
double num = ((((double) Convert.ToInt64(obj2[ "FreeSpace "].ToString())) / 1024) / 1024) / 1024;
return num.ToString( "0.00 ");
}
catch
{
return " ";
}
}
------解决方案--------------------DriveInfo.TotalFreeSpace 属性
注意:此属性在 .NET Framework 2.0 版中是新增的。
获取驱动器上的可用空闲空间总量。
命名空间:System.IO
程序集:mscorlib(在 mscorlib.dll 中)
例:
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine( "Drive {0} ", d.Name);
Console.WriteLine( " File type: {0} ", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine( " Volume label: {0} ", d.VolumeLabel);
Console.WriteLine( " File system: {0} ", d.DriveFormat);
Console.WriteLine(
" Available space to current user:{0, 15} bytes ",
d.AvailableFreeSpace);
Console.WriteLine(
" Total available space: {0, 15} bytes ",
d.TotalFreeSpace);
Console.WriteLine(
" Total size of drive: {0, 15} bytes ",
d.TotalSize);
}
}