FileBackupService.cs 8.8 KB

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