FilePathHelper.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Reflection;
  6. using System.Text.RegularExpressions;
  7. namespace LJLib
  8. {
  9. /// <summary>
  10. /// 文件路径辅助类
  11. /// </summary>
  12. internal sealed class FilePathHelper
  13. {
  14. private static string _executingfile;
  15. /// <summary>
  16. /// 获取当前程序集文件名
  17. /// </summary>
  18. /// <returns></returns>
  19. public static string GetExecutingFile()
  20. {
  21. if (string.IsNullOrEmpty(_executingfile))
  22. {
  23. _executingfile = Assembly.GetExecutingAssembly().GetName().CodeBase;
  24. if (_executingfile.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
  25. {
  26. var regex = new Regex("^file:[\\\\/]*", RegexOptions.IgnoreCase);
  27. _executingfile = regex.Replace(_executingfile, string.Empty);
  28. }
  29. }
  30. return _executingfile;
  31. }
  32. private static string _executingpath;
  33. /// <summary>
  34. /// 获取当前程序集路径
  35. /// </summary>
  36. /// <returns></returns>
  37. public static string GetExecutingPath()
  38. {
  39. if (string.IsNullOrEmpty(_executingpath))
  40. {
  41. _executingpath = Path.GetDirectoryName(GetExecutingFile());
  42. }
  43. return _executingpath;
  44. }
  45. public static List<FileInfo> GetAllSubFiles(DirectoryInfo dir)
  46. {
  47. var rslt = new List<FileInfo>(dir.GetFiles());
  48. var subDirs = dir.GetDirectories();
  49. foreach (var subDir in subDirs)
  50. {
  51. rslt.AddRange(GetAllSubFiles(subDir));
  52. }
  53. return rslt;
  54. }
  55. public static void ClearTmpFile(string extname, string excludePath = null)
  56. {
  57. var rootPath = GetExecutingPath();
  58. var rootDir = new DirectoryInfo(rootPath);
  59. var subfiles = GetAllSubFiles(rootDir);
  60. foreach (var file in subfiles)
  61. {
  62. if (!string.IsNullOrEmpty(excludePath) && file.FullName.StartsWith(excludePath))
  63. {
  64. continue;
  65. }
  66. try
  67. {
  68. if (file.Name.EndsWith(extname))
  69. {
  70. file.Delete();
  71. }
  72. }
  73. catch (Exception ex)
  74. {
  75. Trace.Write(ex);
  76. }
  77. }
  78. }
  79. }
  80. }