You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.5 KiB

3 weeks ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. namespace UpdateServiceLibrary.Helper
  6. {
  7. public class FileController
  8. {
  9. /// <summary>
  10. /// 获取文件哈希值
  11. /// </summary>
  12. /// <param name="fileInfo"></param>
  13. /// <returns></returns>
  14. public static string GetHashCode(FileInfo fileInfo)
  15. {
  16. var hash = SHA1.Create();
  17. byte[] hashcode;
  18. using (var fs = new FileStream(fileInfo.FullName, FileMode.Open))
  19. {
  20. hashcode = hash.ComputeHash(fs);
  21. }
  22. return BitConverter.ToString(hashcode);
  23. }
  24. /// <summary>
  25. /// 移动文件夹下所有文件与路径
  26. /// </summary>
  27. /// <param name="sourcePath"></param>
  28. /// <param name="destPath"></param>
  29. public static void MoveFolder(string sourcePath, string destPath)
  30. {
  31. if (Directory.Exists(sourcePath))
  32. {
  33. if (!Directory.Exists(destPath))
  34. {
  35. //目标目录不存在则创建
  36. try
  37. {
  38. Directory.CreateDirectory(destPath);
  39. }
  40. catch (Exception ex)
  41. {
  42. throw new Exception("创建目标目录失败:" + ex.Message);
  43. }
  44. }
  45. //获得源文件下所有文件
  46. List<string> files = new List<string>(Directory.GetFiles(sourcePath));
  47. files.ForEach(c =>
  48. {
  49. string destFile = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
  50. //覆盖模式
  51. if (File.Exists(destFile))
  52. {
  53. File.Delete(destFile);
  54. }
  55. File.Move(c, destFile);
  56. });
  57. //获得源文件下所有目录文件
  58. List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
  59. folders.ForEach(c =>
  60. {
  61. string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
  62. //采用递归的方法实现
  63. MoveFolder(c, destDir);
  64. });
  65. }
  66. else
  67. {
  68. throw new DirectoryNotFoundException("源目录不存在!");
  69. }
  70. }
  71. }
  72. }