BakTask.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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, //60秒 * 60分钟
  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. if (files.Length > 0)
  44. {
  45. FileInfo[] sortedFiles = files.OrderByDescending(file => file.CreationTime).ToArray();
  46. if (!sortedFiles[0].Name.Equals(todayBakName))
  47. {
  48. //今天未创建备份 开始创建今天的备份
  49. createBakFile(bakFilePath);
  50. }
  51. //判断文件是否超过了7个 超过7个就删除
  52. if (sortedFiles.Length > bakDays)
  53. {
  54. for (int i = bakDays; i < sortedFiles.Length; i++)
  55. {
  56. sortedFiles[i].Delete();
  57. }
  58. }
  59. } else
  60. {
  61. //没有文件 直接创建今天的备份
  62. createBakFile(bakFilePath);
  63. }
  64. }
  65. else
  66. {
  67. dirInfo.Create();
  68. }
  69. }
  70. //创建备份文件
  71. private static void createBakFile(string filePath)
  72. {
  73. using (FileStream fs = new FileStream(filePath, FileMode.Create))
  74. {
  75. BinaryFormatter bf = new BinaryFormatter();
  76. bf.Serialize(fs, MainWindow.appData);
  77. }
  78. }
  79. }
  80. }