CopyUSB/Program.cs

66 lines
1.6 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) =>
{
2023-10-01 13:07:25 +00:00
/*Console.WriteLine("触发器被触发了");*/
2023-10-01 10:12:37 +00:00
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);
}
2023-10-01 13:07:25 +00:00
var copyList = new List<(long, FileInfo, string, string)>();
FileCopy.Copy(driveName, dPath,copyList);
var sortedList = copyList.OrderBy(s => s.Item1).Select(s => s);
/*Console.WriteLine($"元素个数{sortedList.Count()}");*/
foreach (var copyItem in sortedList)
{
Console.WriteLine($"{copyItem.Item4} {copyItem.Item2} --> {copyItem.Item3} {copyItem.Item1 / 1024 / 1024}MB");
try
{
copyItem.Item2.CopyTo(copyItem.Item3, true);
}
catch (Exception ex)
{
Console.WriteLine($"Copy Error {copyItem.Item2}");
/*Console.WriteLine(ex.ToString());*/
}
}
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("一次休眠周期");*/
}