FileBackupService.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. using (var db = new Muse())
  82. {
  83. foreach (var t in temp)
  84. {
  85. //要备份的文件存在
  86. if (File.Exists(t))
  87. {
  88. //文件属于要备份的文件目录
  89. string filepath = DirTool.GetFilePath(t);
  90. BackupPaths path = Paths.FirstOrDefault(x => filepath.Contains(x.Path));
  91. if (path != null)
  92. {
  93. //文件的MD5码以前没有备份过
  94. string md5 = FileTool.GetMD5(t);
  95. bool isback = db.Any<BackupFiles>(x => x.FullPath == t && x.Md5 == md5, null);
  96. if (!isback)
  97. {
  98. string pathname = path.Path;//备份文件夹路径
  99. string pathalias = path.Alias;//备份文件夹别名
  100. string pathfile = t.Substring(pathname.Length, t.Length - pathname.Length);//截取备份文件子目录(相对备份文件夹)
  101. string fileext = "." + DateTimeConvert.CompactString(DateTime.Now) + Path.GetExtension(t);//设置后缀
  102. string fullpath = DirTool.Combine(R.Settings.FileBackup.FileManBackup, pathalias, pathfile + fileext);//组合路径
  103. //删除冗余
  104. DeleteExcess(t);
  105. //备份文件
  106. BackupFile(t, fullpath, md5);
  107. _FileCount++;
  108. }
  109. }
  110. }
  111. }
  112. }
  113. }
  114. Thread.Sleep(R.Settings.FileBackup.BACK_UP_INTERVAL);
  115. }
  116. }
  117. /// <summary>
  118. /// 读取备份文件总数
  119. /// </summary>
  120. private void ReadBackupFileCount()
  121. {
  122. //统计备份文件总数
  123. using (var db = new Muse())
  124. {
  125. _FileCount = db.Do<BackupFiles>().Count();
  126. }
  127. }
  128. /// <summary>
  129. /// 读取备份文件夹列表
  130. /// </summary>
  131. private void ReadBackupPaths()
  132. {
  133. //读取要备份的文件路径列表
  134. using (var db = new Muse())
  135. {
  136. Paths = db.GetAll<BackupPaths>(null, false).ToList();
  137. if (ListTool.HasElements(Paths))
  138. {
  139. foreach (var p in Paths)
  140. {
  141. AddToWatcherPath(p.Path);
  142. }
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// 初始读取文件并备份
  148. /// </summary>
  149. public void DefaultBackupFile(string path)
  150. {
  151. //读取本地文件夹中的所有文件列表
  152. List<string> files = FileTool.GetAllFile(path);
  153. if (ListTool.HasElements(files))
  154. {
  155. foreach (var file in files)
  156. {
  157. try
  158. {
  159. string lastwritetime = DateTimeConvert.StandardString(File.GetLastWriteTime(file));
  160. using (var db = new Muse())
  161. {
  162. BackupFiles backfile = db.Get<BackupFiles>(x => x.FullPath == file && x.LastWriteTime == lastwritetime, null);
  163. if (backfile == null) AddToBackupFiles(file);
  164. }
  165. }
  166. catch (Exception e) { }
  167. }
  168. }
  169. }
  170. /// <summary>
  171. /// 添加要备份的文件到备份计划列表
  172. /// </summary>
  173. /// <param name="fullpath"></param>
  174. private void AddToBackupFiles(string fullpath)
  175. {
  176. if (Paths.Any(x => fullpath.Contains(x.Path)))
  177. {
  178. //变动的是文件且文件存在
  179. if (FileTool.IsFile(fullpath))
  180. {
  181. //添加到备份列表
  182. if (!BackupFiles.Contains(fullpath)) BackupFiles.Add(fullpath);
  183. //UIDgvFileAdd(e.Name, e.FullPath, e.ChangeType.ToString());
  184. }
  185. }
  186. }
  187. /// <summary>
  188. /// 添加要备份的文件夹
  189. /// </summary>
  190. /// <param name="path"></param>
  191. public void AddToWatcherPath(string path)
  192. {
  193. Watcher.AddPath(path);//添加要备份的文件夹
  194. DefaultBackupFile(path);//常规检查备份文件夹
  195. }
  196. /// <summary>
  197. /// 删除超过备份最大次数的项
  198. /// </summary>
  199. private void DeleteExcess(string path)
  200. {
  201. using (var db = new Muse())
  202. {
  203. int count = db.Do<BackupFiles>().Count(x => x.FullPath == path);
  204. if (count >= R.Settings.FileBackup.BACK_UP_COUNT)
  205. {
  206. var fs = db.Gets<BackupFiles>(x => x.FullPath == path, null).OrderBy(x => x.Id).ToList();
  207. if (ListTool.HasElements(fs))
  208. {
  209. for (int i = 0; i <= count - R.Settings.FileBackup.BACK_UP_COUNT; i++)
  210. {
  211. try
  212. {
  213. File.Delete(fs[i].BackupFullPath);
  214. db.Del(fs[i], true);
  215. }
  216. catch (Exception e) { }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// 备份文件
  224. /// </summary>
  225. /// <param name="path"></param>
  226. /// <param name="newpath"></param>
  227. private void BackupFile(string path, string newpath, string md5)
  228. {
  229. using (var db = new Muse())
  230. {
  231. try
  232. {
  233. if (DirTool.Create(DirTool.GetFilePath(newpath)))
  234. {
  235. string lastwritetime = DateTimeConvert.StandardString(File.GetLastWriteTime(path));
  236. File.Copy(path, newpath, true);
  237. db.Add(new BackupFiles()
  238. {
  239. FullPath = path,
  240. BackupFullPath = newpath,
  241. Size = FileTool.Size(path),
  242. BackupTime = DateTimeConvert.StandardString(DateTime.Now),
  243. LastWriteTime = lastwritetime,
  244. Md5 = md5,
  245. });
  246. }
  247. }
  248. catch (Exception e) { }
  249. }
  250. }
  251. }
  252. }