FileHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace KYFramework
  5. {
  6. public static class FileHelper
  7. {
  8. public static List<string> GetAllFiles(string dir, string searchPattern = "*")
  9. {
  10. List<string> list = new List<string>();
  11. GetAllFiles(list, dir, searchPattern);
  12. return list;
  13. }
  14. public static void GetAllFiles(List<string> files, string dir, string searchPattern = "*")
  15. {
  16. string[] fls = Directory.GetFiles(dir);
  17. foreach (string fl in fls)
  18. {
  19. files.Add(fl);
  20. }
  21. string[] subDirs = Directory.GetDirectories(dir);
  22. foreach (string subDir in subDirs)
  23. {
  24. GetAllFiles(files, subDir, searchPattern);
  25. }
  26. }
  27. public static void CleanDirectory(string dir)
  28. {
  29. if (!Directory.Exists(dir))
  30. {
  31. return;
  32. }
  33. foreach (string subdir in Directory.GetDirectories(dir))
  34. {
  35. Directory.Delete(subdir, true);
  36. }
  37. foreach (string subFile in Directory.GetFiles(dir))
  38. {
  39. File.Delete(subFile);
  40. }
  41. }
  42. public static void CopyDirectory(string srcDir, string tgtDir)
  43. {
  44. DirectoryInfo source = new DirectoryInfo(srcDir);
  45. DirectoryInfo target = new DirectoryInfo(tgtDir);
  46. if (target.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
  47. {
  48. throw new Exception("父目录不能拷贝到子目录!");
  49. }
  50. if (!source.Exists)
  51. {
  52. return;
  53. }
  54. if (!target.Exists)
  55. {
  56. target.Create();
  57. }
  58. FileInfo[] files = source.GetFiles();
  59. for (int i = 0; i < files.Length; i++)
  60. {
  61. File.Copy(files[i].FullName, Path.Combine(target.FullName, files[i].Name), true);
  62. }
  63. DirectoryInfo[] dirs = source.GetDirectories();
  64. for (int j = 0; j < dirs.Length; j++)
  65. {
  66. CopyDirectory(dirs[j].FullName, Path.Combine(target.FullName, dirs[j].Name));
  67. }
  68. }
  69. public static void ReplaceExtensionName(string srcDir, string extensionName, string newExtensionName)
  70. {
  71. if (Directory.Exists(srcDir))
  72. {
  73. string[] fls = Directory.GetFiles(srcDir);
  74. foreach (string fl in fls)
  75. {
  76. if (fl.EndsWith(extensionName))
  77. {
  78. File.Move(fl, fl.Substring(0, fl.IndexOf(extensionName)) + newExtensionName);
  79. File.Delete(fl);
  80. }
  81. }
  82. string[] subDirs = Directory.GetDirectories(srcDir);
  83. foreach (string subDir in subDirs)
  84. {
  85. ReplaceExtensionName(subDir, extensionName, newExtensionName);
  86. }
  87. }
  88. }
  89. }
  90. }