用C#的两种取得硬盘剩余空间方法
1.[DllImport("kernel32.dll")]
private static extern bool GetDiskFreeSpaceEx(
string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
/// <summary>
/// 取得磁盘剩余空间
/// </summary>
/// <param name="driveDirectoryName">驱动器名</param>
/// <returns>剩余空间</returns>
private static ulong GetFreeSpace(string driveDirectoryName)
{
ulong freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
if (!driveDirectoryName.EndsWith("://"))
{
driveDirectoryName += "://";
}
GetDiskFreeSpaceEx(driveDirectoryName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes);
return freeBytesAvailable;
}
private static extern bool GetDiskFreeSpaceEx(
string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);
/// <summary>
/// 取得磁盘剩余空间
/// </summary>
/// <param name="driveDirectoryName">驱动器名</param>
/// <returns>剩余空间</returns>
private static ulong GetFreeSpace(string driveDirectoryName)
{
ulong freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
if (!driveDirectoryName.EndsWith("://"))
{
driveDirectoryName += "://";
}
GetDiskFreeSpaceEx(driveDirectoryName, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes);
return freeBytesAvailable;
}
2.
using System.Management;
private void ListDiskQuota()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
Console.WriteLine( "Disk Volume" + "/t" + "FreeSpace" );
foreach( ManagementObject disk in searcher.Get() )
{
Console.WriteLine( disk["Caption"] + "/t" + disk["FreeSpace"] );
}
}
private void ListDiskQuota()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk");
Console.WriteLine( "Disk Volume" + "/t" + "FreeSpace" );
foreach( ManagementObject disk in searcher.Get() )
{
Console.WriteLine( disk["Caption"] + "/t" + disk["FreeSpace"] );
}
}