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) => { /*Console.WriteLine("触发器被触发了");*/ 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); } 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());*/ } } Console.WriteLine("\n--------------Scaned and waiting--------------\n"); }; managementEventWatcher.Start(); // 让程序保持运行状态 while (true) { Thread.Sleep(1000); /*Console.WriteLine("一次休眠周期");*/ }