FileHelper.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. namespace IES.ExamServer.Helpers
  2. {
  3. public class FileHelper
  4. {
  5. /// <summary>
  6. /// 删除整个文件夹及其内容
  7. /// </summary>
  8. /// <param name="folderPath"></param>
  9. /// <returns></returns>
  10. public static bool DeleteFolder(string folderPath)
  11. {
  12. bool result = false;
  13. try
  14. {
  15. if (Directory.Exists(folderPath))
  16. {
  17. // 删除文件夹及其所有内容
  18. Directory.Delete(folderPath, true);
  19. result = true;
  20. //Console.WriteLine($"Folder '{folderPath}' deleted successfully.");
  21. }
  22. else
  23. {
  24. //Console.WriteLine($"Folder '{folderPath}' does not exist.");
  25. result = true;
  26. }
  27. }
  28. catch (Exception ex)
  29. {
  30. result = false;
  31. //Console.WriteLine($"Error: {ex.Message}");
  32. }
  33. return result;
  34. }
  35. /// <summary>
  36. /// 列出文件夹下的所有子文件及子文件夹的子文件
  37. /// </summary>
  38. /// <param name="directoryPath"></param>
  39. /// <param name="filter">获取指定匹配模式的文件,如后缀, local.json</param>
  40. /// <returns></returns>
  41. public static List<string> ListAllFiles(string directoryPath, string? filter = null)
  42. {
  43. List<string> filePaths = new List<string>();
  44. DirectoryInfo dirInfo = new DirectoryInfo(directoryPath);
  45. // 获取目录下的所有文件(包括子目录中的文件)
  46. FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories);
  47. foreach (FileInfo file in files)
  48. {
  49. if (string.IsNullOrWhiteSpace(filter))
  50. {
  51. filePaths.Add(file.FullName);
  52. continue;
  53. }
  54. else
  55. {
  56. if (file.FullName.Contains(filter))
  57. {
  58. filePaths.Add(file.FullName);
  59. }
  60. }
  61. }
  62. return filePaths;
  63. }
  64. }
  65. }