介绍:
有一个控制台命令是创建指定大小的空文件,因此我想制作一个一键填充剩余磁盘空间的坑人小程序。
想要填充剩余容量,就要先获取所有本地磁盘的剩余空间,这个程序就是用来做这个的。
项目类型为c#控制台,程序源码全部如下:
注意System.Management这个命名空间只用using引入是没有用的,还要手动去引用程序集。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using static System.Console; using System.Management;//需要手动添加程序集的引用,这里的引用不是指命名空间的导入! namespace ConsoleApp3 { class Program { static void Main(string[] args) { Program aa = new Program(); foreach(string s in aa.GetRemovableDeviceID()) { long freespace = aa.GetHardDiskSpace(s); WriteLine(s+" "+ (freespace-1) +" GB");//向下取整并-1GB } ReadKey(); } //单位GB public long GetHardDiskSpace(string str_HardDiskName) { long totalSize = 0; str_HardDiskName = str_HardDiskName + "\\"; DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { if (drive.Name == str_HardDiskName) { totalSize = drive.TotalFreeSpace / (1024 * 1024 * 1024); } } return totalSize; } public List<string> GetRemovableDeviceID() { List<string> deviceIDs = new List<string>(); ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * From Win32_LogicalDisk "); ManagementObjectCollection queryCollection = query.Get(); foreach (ManagementObject mo in queryCollection) { switch (int.Parse(mo["DriveType"].ToString())) { case (int)DriveType.Removable: //可以移动磁盘 { //MessageBox.Show("可以移动磁盘"); deviceIDs.Add(mo["DeviceID"].ToString()); break; } case (int)DriveType.Fixed: //本地磁盘 { //MessageBox.Show("本地磁盘"); deviceIDs.Add(mo["DeviceID"].ToString()); break; } default: //defalut to folder { //MessageBox.Show("驱动器类型未知 "); break; } } } return deviceIDs; } } }
程序运行结果如下: