Compare commits

...

5 Commits
2.0 ... master

Author SHA1 Message Date
cbb5b5588b 从大到小复制逻辑 2023-10-14 21:55:20 +08:00
872644e47e 修复错误判断 2023-10-14 14:46:11 +08:00
745d2e2b6c 使用数据库维护文件管理,修复文件管理BUG 2023-10-14 14:35:24 +08:00
c07715536c 更改try catch逻辑 2023-10-14 12:57:12 +08:00
3a3f866bf4 增加了数据库优化策略 2023-10-14 00:29:15 +08:00
5 changed files with 276 additions and 191 deletions

View File

@ -8,6 +8,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.12" />
<PackageReference Include="System.Management" Version="7.0.2" /> <PackageReference Include="System.Management" Version="7.0.2" />
</ItemGroup> </ItemGroup>

View File

@ -1,4 +1,5 @@
using System; using CopyUSB.MyDB;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
@ -15,8 +16,32 @@ public class CopyList
} }
public class FileCopy public class FileCopy
{ {
private static void ListFileInDic(DirectoryInfo source,DirectoryInfo target,List<(FileInfo,FileInfo)> values)
{
foreach (var file in source.GetFiles())
{
/*Debug.WriteLine(Path.Join(target.FullName, file.Name));*/
try
{
values.Add((file, new FileInfo(Path.Join(target.FullName, file.Name))));
}catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
foreach(var dir in source.GetDirectories())
{
try
{
ListFileInDic(dir, new DirectoryInfo(Path.Join(target.FullName, dir.Name)), values);
}catch(Exception ex)
{
Debug.WriteLine(ex);
}
}
}
public static void Copy(string source,string des, List<(long, FileInfo, string, string)> copyList) public static void Copy(string source,string des)
{ {
try try
{ {
@ -28,41 +53,55 @@ public class FileCopy
{ {
desDir.Create(); desDir.Create();
} }
//遍历目录 var cpFileList = new List<(FileInfo, FileInfo)>();
foreach (var subDir in sourceDir.GetDirectories()) ListFileInDic(sourceDir, desDir, cpFileList);
var sortedFile = cpFileList.OrderBy(o=>o.Item1.Length).ToList();
using (var fileInfoDb = new FileInfoDb())
{ {
Copy(subDir.FullName, Path.Combine(desDir.FullName, subDir.Name), copyList); foreach(var file in sortedFile)
{
try
{
var tryGetFileDb = fileInfoDb.Files.Where(w=>w.Path==file.Item2.FullName).FirstOrDefault();
if (tryGetFileDb == null)
{
tryGetFileDb = new MyDB.Class.FileInfoTable();
tryGetFileDb.NeedChange = true;
tryGetFileDb.Path = file.Item2.FullName;
tryGetFileDb.Size = file.Item1.Length;
if (!file.Item2.Directory.Exists)
{
file.Item2.Directory.Create();
} }
foreach (var file in sourceDir.GetFiles()) file.Item1.CopyTo(file.Item2.FullName,true);
{ fileInfoDb.Files.Add(tryGetFileDb);
string destinationFile = Path.Combine(desDir.FullName, file.Name); Debug.WriteLine($"Copied and added into Db {file.Item1.FullName} --> {file.Item2.FullName}");
if (File.Exists(destinationFile))
{
var desFileInfo = new FileInfo(destinationFile);
if (desFileInfo.Length != file.Length)
{
/*Console.WriteLine($"Renew {file} --> {destinationFile}");*/
copyList.Add((file.Length,file, destinationFile,"Renew"));
/*file.CopyTo(destinationFile, true);*/
} }
else else
{ {
Debug.WriteLine($"Same {file} --> {destinationFile} {file.Length/1024/1024}MB"); if(tryGetFileDb.Size == file.Item1.Length)
/*copyList.Add((file, destinationFile, 0, "Same"));*/ {
} Debug.WriteLine($"Found Same file from db {file.Item1.FullName}");
} }
else else
{ {
/*Console.WriteLine($"NewFile {file} --> {destinationFile}");*/ file.Item1.CopyTo (file.Item2.FullName,true);
copyList.Add((file.Length,file, destinationFile, "NewFile")); tryGetFileDb.Size = (int)file.Item1.Length;
tryGetFileDb.NeedChange= true;
Debug.WriteLine($"Renew {file.Item1.FullName}");
} }
} }
}catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
fileInfoDb.SaveChanges();
}
} }
catch (Exception ex) catch (Exception ex)
{ {
Debug.WriteLine(ex.ToString());
/*Console.WriteLine($"Copy Error {source}");*/ /*Console.WriteLine($"Copy Error {source}");*/
/*Console.WriteLine(ex.ToString());*/ /*Console.WriteLine(ex.ToString());*/
} }
@ -70,9 +109,13 @@ public class FileCopy
public static long DicFileNum(string source) public static long DicFileNum(string source)
{ {
long num = 0; long num = 0;
FileNum(source,ref num); using (var fileInfoDb = new FileInfoDb())
Console.WriteLine($"Totle Dic Num is {num}"); {
return num; num = fileInfoDb.Files.Where(w=>w.NeedChange==true).Count();
/*FileNum(source,ref num);*/
Debug.WriteLine($"Totle Dic Num is {num} (From Db)");
}
return num<0?0:num;
} }
private static void FileNum(string source, ref long num) private static void FileNum(string source, ref long num)
{ {
@ -88,60 +131,63 @@ public class FileCopy
} }
catch (Exception ex) catch (Exception ex)
{ {
Debug.WriteLine(ex.ToString());
/*Console.WriteLine($"Copy Error {source}");*/ /*Console.WriteLine($"Copy Error {source}");*/
/*Console.WriteLine(ex.ToString());*/ /*Console.WriteLine(ex.ToString());*/
} }
} }
public static void SimpleCopy(string source, string des,ref Int64 doneNum) public static void SimpleCopy(string des,string baseDic , ref Int64 doneNum)
{
/*try
{*/
var desDir = new DirectoryInfo(des);
//数据库查找需要更改的数据
using (var fileInfoDb = new FileInfoDb())
{
var allNeedChangeFile = fileInfoDb.Files.Where(w => w.NeedChange == true).OrderBy(o => o.Size).ToList();
foreach (var file in allNeedChangeFile)
{
var desInfo = new FileInfo(Path.Join(des, file.Path.Replace(baseDic, "")));
var fileInfo = new FileInfo(file.Path);
if (!fileInfo.Exists)
{
Debug.WriteLine($"Cannot Find File In Computer {fileInfo.FullName}");
file.NeedChange= false;
continue;
}
if (!desInfo.Directory.Exists)
{ {
try try
{ {
var sourceDir = new DirectoryInfo(source); desInfo.Directory.Create();
var desDir = new DirectoryInfo(des); }catch(Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
try
{
fileInfo.CopyTo(desInfo.FullName, true);
fileInfo.Delete();
file.NeedChange = false;
Debug.WriteLine($"moved the file and marked into Db {fileInfo.FullName} --> {desInfo.FullName}");
}
catch(Exception ex)
{
Debug.WriteLine($"Error: moved the file and marked into Db {fileInfo.FullName} --> {desInfo.FullName}\n{ex.ToString()}");
}
// 确保目标目录存在
if (!desDir.Exists)
{
desDir.Create();
}
//遍历目录
foreach (var subDir in sourceDir.GetDirectories())
{
SimpleCopy(subDir.FullName, Path.Combine(desDir.FullName, subDir.Name),ref doneNum);
}
foreach (var file in sourceDir.GetFiles())
{
string destinationFile = Path.Combine(desDir.FullName, file.Name);
if (File.Exists(destinationFile))
{
var desFileInfo = new FileInfo(destinationFile);
if (desFileInfo.Length != file.Length)
{
Debug.WriteLine($"Renew {file} --> {destinationFile}");
/*copyList.Add((file.Length, file, destinationFile, "Renew"));*/
file.CopyTo(destinationFile, true);
}
else
{
Debug.WriteLine($"Same {file} --> {destinationFile} {file.Length / 1024 / 1024}MB");
/*copyList.Add((file, destinationFile, 0, "Same"));*/
}
}
else
{
Debug.WriteLine($"NewFile {file} --> {destinationFile}");
/*copyList.Add((file.Length, file, destinationFile, "NewFile"));*/
file.CopyTo(destinationFile, true);
}
doneNum++; doneNum++;
} }
fileInfoDb.SaveChanges();
} }
/*}
catch (Exception ex) catch (Exception ex)
{ {
/*Console.WriteLine($"Copy Error {source}");*/ Debug.WriteLine(ex.ToString());
/*Console.WriteLine(ex.ToString());*/ *//*Console.WriteLine($"Copy Error {source}");*/
} /*Console.WriteLine(ex.ToString());*//*
}*/
} }
} }

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyUSB.MyDB.Class;
public class FileInfoTable
{
public long Id { get; set; }
public long Size { get; set; }
public string Path { get; set; }
public bool NeedChange { get; set; } = true;
}

23
MyDB/FileInfoDb.cs Normal file
View File

@ -0,0 +1,23 @@
using CopyUSB.MyDB.Class;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CopyUSB.MyDB;
public class FileInfoDb:DbContext
{
public FileInfoDb()
{
this.Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
/*base.OnConfiguring(optionsBuilder);*/
optionsBuilder.UseSqlite("Data Source=./fileInfo.db");
}
public DbSet<FileInfoTable> Files { get; set; }
}

View File

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