FileBackupService.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using Oreo.FileMan.DatabaseEngine;
  2. using Oreo.FileMan.Models;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Y.Utils.DataUtils.Collections;
  10. using Y.Utils.DataUtils.DateTimeUtils;
  11. using Y.Utils.IOUtils.FileManUtils;
  12. using Y.Utils.IOUtils.FileUtils;
  13. using Y.Utils.IOUtils.PathUtils;
  14. namespace Oreo.FileMan.Services
  15. {
  16. public class FileBackupService
  17. {
  18. private FileWatcher Watcher = new FileWatcher(null);
  19. public string FileManBackup = @"D:\temp\FileManBackup\";
  20. public List<BackupPaths> Paths = new List<BackupPaths>();
  21. List<string> BackupFiles = new List<string>();
  22. int BACK_UP_INTERVAL = 5 * 1000;
  23. int BACK_UP_COUNT = 5;
  24. bool IsStart = false;
  25. public void Start()
  26. {
  27. if (!IsStart)
  28. {
  29. IsStart = true;
  30. Watcher.EventHandler += WatcherChangedEvent;
  31. Watcher.Start();//启动文件变动监听
  32. Task.Factory.StartNew(() =>
  33. {
  34. ReadBackupPaths();//读取备份文件夹列表
  35. if (ListTool.HasElements(Paths))
  36. {
  37. foreach (var p in Paths)
  38. {
  39. DefaultBackupFile(p.Path);//常规检查备份
  40. }
  41. }
  42. BackupFileTask();//开始定时备份任务
  43. });
  44. }
  45. }
  46. public void Stop()
  47. {
  48. if (IsStart)
  49. {
  50. IsStart = false;
  51. }
  52. }
  53. /// <summary>
  54. /// 文件发生变动事件
  55. /// </summary>
  56. /// <param name="sender"></param>
  57. /// <param name="e"></param>
  58. private void WatcherChangedEvent(object sender, FileWatcherEventArgs e)
  59. {
  60. AddToBackupFiles(e.FullPath);
  61. }
  62. /// <summary>
  63. /// 定时处理要备份的文件任务
  64. /// </summary>
  65. private void BackupFileTask()
  66. {
  67. while (IsStart)
  68. {
  69. if (ListTool.HasElements(BackupFiles))
  70. {
  71. //获取要备份的文件列表并复制样本
  72. List<string> temp;
  73. lock (BackupFiles)
  74. {
  75. temp = BackupFiles;
  76. BackupFiles = new List<string>();
  77. }
  78. foreach (var t in temp)
  79. {
  80. if (File.Exists(t))
  81. {
  82. string filepath = DirTool.GetFilePath(t);
  83. BackupPaths path = Paths.FirstOrDefault(x => filepath.Contains(x.Path));
  84. if (path != null)
  85. {
  86. string pathname = path.Path;
  87. string pathalias = path.Alias;
  88. string pathfile = t.Substring(pathname.Length, t.Length - pathname.Length);
  89. string fileext = DateTimeConvert.CompactString(DateTime.Now);
  90. string fullpath = DirTool.Combine(FileManBackup, pathalias, pathfile + "." + fileext);
  91. //删除冗余
  92. DeleteExcess(t);
  93. //备份文件
  94. BackupFile(t, fullpath);
  95. }
  96. }
  97. }
  98. }
  99. Thread.Sleep(BACK_UP_INTERVAL);
  100. }
  101. }
  102. /// <summary>
  103. /// 读取备份文件夹列表
  104. /// </summary>
  105. private void ReadBackupPaths()
  106. {
  107. //读取要备份的文件路径列表
  108. using (var db = new Muse())
  109. {
  110. Paths = db.GetAll<BackupPaths>(null, false).ToList();
  111. if (ListTool.HasElements(Paths))
  112. {
  113. foreach (var p in Paths)
  114. {
  115. AddToWatcherPath(p.Path);
  116. }
  117. }
  118. }
  119. }
  120. /// <summary>
  121. /// 初始读取文件并备份
  122. /// </summary>
  123. public void DefaultBackupFile(string path)
  124. {
  125. //读取本地文件夹中的所有文件列表
  126. List<string> files = FileTool.GetAllFile(path);
  127. if (ListTool.HasElements(files))
  128. {
  129. foreach (var file in files)
  130. {
  131. try
  132. {
  133. string lastwritetime = DateTimeConvert.StandardString(File.GetLastWriteTime(file));
  134. using (var db = new Muse())
  135. {
  136. BackupFiles backfile = db.Get<BackupFiles>(x => x.FullPath == file && x.LastWriteTime == lastwritetime, null);
  137. if (backfile == null) AddToBackupFiles(file);
  138. }
  139. }
  140. catch (Exception e) { }
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// 添加要备份的文件到备份计划列表
  146. /// </summary>
  147. /// <param name="fullpath"></param>
  148. private void AddToBackupFiles(string fullpath)
  149. {
  150. if (Paths.Any(x => fullpath.Contains(x.Path)))
  151. {
  152. //变动的是文件且文件存在
  153. if (FileTool.IsFile(fullpath))
  154. {
  155. //添加到备份列表
  156. if (!BackupFiles.Contains(fullpath)) BackupFiles.Add(fullpath);
  157. //UIDgvFileAdd(e.Name, e.FullPath, e.ChangeType.ToString());
  158. }
  159. }
  160. }
  161. /// <summary>
  162. /// 添加要备份的文件夹
  163. /// </summary>
  164. /// <param name="path"></param>
  165. public void AddToWatcherPath(string path)
  166. {
  167. Watcher.AddPath(path);//添加要备份的文件夹
  168. DefaultBackupFile(path);//常规检查备份文件夹
  169. }
  170. /// <summary>
  171. /// 删除超过备份最大次数的项
  172. /// </summary>
  173. private void DeleteExcess(string path)
  174. {
  175. using (var db = new Muse())
  176. {
  177. int count = db.Do<BackupFiles>().Count(x => x.FullPath == path);
  178. if (count >= BACK_UP_COUNT)
  179. {
  180. var fs = db.Gets<BackupFiles>(x => x.FullPath == path, null).OrderBy(x => x.Id).ToList();
  181. if (ListTool.HasElements(fs))
  182. {
  183. for (int i = 0; i <= count - BACK_UP_COUNT; i++)
  184. {
  185. try
  186. {
  187. File.Delete(fs[i].BackupFullPath);
  188. db.Del(fs[i], true);
  189. }
  190. catch (Exception e) { }
  191. }
  192. }
  193. }
  194. }
  195. }
  196. /// <summary>
  197. /// 备份文件
  198. /// </summary>
  199. /// <param name="path"></param>
  200. /// <param name="newpath"></param>
  201. private void BackupFile(string path, string newpath)
  202. {
  203. using (var db = new Muse())
  204. {
  205. try
  206. {
  207. if (DirTool.Create(DirTool.GetFilePath(newpath)))
  208. {
  209. string lastwritetime = DateTimeConvert.StandardString(File.GetLastWriteTime(path));
  210. File.Copy(path, newpath, true);
  211. db.Add(new BackupFiles()
  212. {
  213. FullPath = path,
  214. BackupFullPath = newpath,
  215. Size = FileTool.Size(path),
  216. BackupTime = DateTimeConvert.StandardString(DateTime.Now),
  217. LastWriteTime = lastwritetime,
  218. });
  219. }
  220. }
  221. catch (Exception e) { }
  222. }
  223. }
  224. }
  225. }