BakTask.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using GeekDesk.Constant;
  2. using GeekDesk.ViewModel;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Runtime.Serialization.Formatters.Binary;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace GeekDesk.Task
  14. {
  15. internal class BakTask
  16. {
  17. public static void Start()
  18. {
  19. System.Timers.Timer timer = new System.Timers.Timer
  20. {
  21. Enabled = true,
  22. Interval = 60 * 1000 * 60 * 2, //60秒 * 60 * 2 2小时触发一次
  23. //Interval = 6000,
  24. };
  25. timer.Start();
  26. timer.Elapsed += Timer_Elapsed;
  27. }
  28. private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  29. {
  30. DirectoryInfo dirInfo = new DirectoryInfo(Constants.DATA_FILE_BAK_DIR_PATH);
  31. string todayBakName = DateTime.Now.ToString("yyyy-MM-dd") + ".bak";
  32. string bakDaysStr = ConfigurationManager.AppSettings["BakDays"];
  33. int bakDays = 7;
  34. if (bakDaysStr != null && !"".Equals(bakDaysStr.Trim()))
  35. {
  36. bakDays = Int32.Parse(bakDaysStr.Trim());
  37. }
  38. string bakFilePath = Constants.DATA_FILE_BAK_DIR_PATH + "\\" + todayBakName;
  39. if (dirInfo.Exists)
  40. {
  41. // 获取文件信息并按创建时间倒序排序
  42. FileInfo[] files = dirInfo.GetFiles()
  43. .Where(f => f.Extension.Equals(".bak", StringComparison.OrdinalIgnoreCase)).ToArray();
  44. if (files.Length > 0)
  45. {
  46. FileInfo[] sortedFiles = files.OrderByDescending(file => file.CreationTime).ToArray();
  47. if (!sortedFiles[0].Name.Equals(todayBakName))
  48. {
  49. //今天未创建备份 开始创建今天的备份
  50. createBakFile(bakFilePath);
  51. }
  52. //判断文件是否超过了7个 超过7个就删除
  53. if (sortedFiles.Length > bakDays)
  54. {
  55. for (int i = bakDays; i < sortedFiles.Length; i++)
  56. {
  57. sortedFiles[i].Delete();
  58. }
  59. }
  60. } else
  61. {
  62. //没有文件 直接创建今天的备份
  63. createBakFile(bakFilePath);
  64. }
  65. }
  66. else
  67. {
  68. dirInfo.Create();
  69. }
  70. }
  71. //创建备份文件
  72. private static void createBakFile(string filePath)
  73. {
  74. using (FileStream fs = new FileStream(filePath, FileMode.Create))
  75. {
  76. BinaryFormatter bf = new BinaryFormatter();
  77. bf.Serialize(fs, MainWindow.appData);
  78. }
  79. }
  80. }
  81. }