CopyUSB/Program.cs

46 lines
1.0 KiB
C#
Raw Normal View History

2023-10-01 10:12:37 +00:00
using CopyUSB;
using System.Management;
static string GetVolumeLabel(string driveName)
{
try
{
DriveInfo driveInfo = new DriveInfo(driveName);
return driveInfo.VolumeLabel;
}
catch (Exception)
{
return null;
}
}
string query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2";
ManagementEventWatcher managementEventWatcher = new(query);
Console.WriteLine("Waiting for USB...");
managementEventWatcher.EventArrived += (s, e) =>
{
string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
string dPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "USBCopy", GetVolumeLabel(driveName));
Console.WriteLine($"Detected: {driveName} || Save To -> : {dPath}");
if (!Directory.Exists(dPath))
{
Directory.CreateDirectory(dPath);
}
FileCopy.Copy(driveName, dPath);
2023-10-01 10:56:34 +00:00
Console.WriteLine("\n--------------Scaned and waiting--------------\n");
2023-10-01 10:12:37 +00:00
};
managementEventWatcher.Start();
// 让程序保持运行状态
while (true)
{
Thread.Sleep(1000);
/*Console.WriteLine("一次休眠周期");*/
}