FileTool.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Y.Utils.BaseUtils;
  6. namespace Y.Utils.FileUtils
  7. {
  8. public class FileTool
  9. {
  10. public static List<string> GetFile(string path, string pattern = "*")
  11. {
  12. if (Directory.Exists(path))
  13. try
  14. {
  15. List<string> result = Directory.EnumerateFiles(path, pattern).ToList();
  16. return result;
  17. }
  18. catch (Exception e) { }
  19. return null;
  20. }
  21. public static List<string> GetAllFile(string path, string pattern = "*")
  22. {
  23. List<string> result = null;
  24. try
  25. {
  26. result = Directory.EnumerateFiles(path, pattern, SearchOption.AllDirectories).ToList();
  27. }
  28. catch (Exception e) { }
  29. return result;
  30. }
  31. public static List<string> GetAllFile(string path, string[] pattern)
  32. {
  33. List<string> result = new List<string>();
  34. if (!ListTool.IsNullOrEmpty(pattern))
  35. {
  36. foreach (var p in pattern)
  37. {
  38. List<string> temp = GetAllFile(path, p).ToList();
  39. if (!ListTool.IsNullOrEmpty(temp)) result.AddRange(temp);
  40. }
  41. }
  42. return result;
  43. }
  44. public static List<string> GetAllFile(string[] paths, string[] patterns)
  45. {
  46. List<string> result = new List<string>();
  47. if (!ListTool.IsNullOrEmpty(paths))
  48. {
  49. foreach(var path in paths)
  50. {
  51. if (!ListTool.IsNullOrEmpty(patterns))
  52. {
  53. foreach (var pattern in patterns)
  54. {
  55. List<string> temp = GetAllFile(path, pattern).ToList();
  56. if (!ListTool.IsNullOrEmpty(temp)) result.AddRange(temp);
  57. }
  58. }else
  59. {
  60. List<string> temp = GetAllFile(path).ToList();
  61. if (!ListTool.IsNullOrEmpty(temp)) result.AddRange(temp);
  62. }
  63. }
  64. }
  65. return result;
  66. }
  67. public static bool Delete(string file)
  68. {
  69. try
  70. {
  71. if (File.Exists(file))
  72. {
  73. File.Delete(file);
  74. return true;
  75. }
  76. else
  77. {
  78. return true;
  79. }
  80. }
  81. catch { }
  82. return false;
  83. }
  84. public static bool Delete(string[] files)
  85. {
  86. bool result = true;
  87. if (!ListTool.IsNullOrEmpty(files))
  88. {
  89. foreach (var file in files)
  90. {
  91. result = result || Delete(file);
  92. }
  93. }
  94. return result;
  95. }
  96. }
  97. }