这个只引用System.IO
感觉有点没节操,就是定时执行 DriveInfo.GetDrives();
但是架不住简单不是吗!也是个思路
DriveInfo[] s = DriveInfo.GetDrives();
foreach (DriveInfo i in s)
{
string name = i.Name;
Console.WriteLine($"设备名称:{name}\n\t设备类型:{i.DriveType}");
if (i.DriveType == DriveType.Removable)
{
long freespace = i.TotalFreeSpace;//空闲空间大小
long maxspace = i.TotalSize;//存储空间大小
i.VolumeLabel = "h";//获取或设置驱动器的卷标。
string VolumeLabel = i.VolumeLabel;
Console.WriteLine("发现U盘或移动硬盘");
}
}
直接上例子:
public static void Main(string[] args)
{
Timer timer = new Timer(10*1000);
timer.Elapsed += Timer_Elapsed;
timer.Enabled = true;
timer.Start();
Console.ReadKey();
}
private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
DriveInfo[] s = DriveInfo.GetDrives();
uint flag = 0;
foreach (DriveInfo i in s)
{
string name = i.Name;
//Console.WriteLine($"设备名称:{name}\n\t设备类型:{i.DriveType}");
if (i.DriveType == DriveType.Removable)
{
flag++;
long freespace = i.TotalFreeSpace/(1024*1024 * 1024);//空闲空间大小
long maxspace = i.TotalSize/ (1024 * 1024 * 1024);//存储空间大小
i.VolumeLabel = "h";//获取或设置驱动器的卷标。
string VolumeLabel = i.VolumeLabel;
Console.WriteLine($"发现U盘或移动硬盘{VolumeLabel}:总存储{maxspace}GB,空闲{freespace}GB");
}
}
if(flag<=0)
Console.WriteLine("未发现U盘或移动硬盘");
flag = 0;
}