C#遍历获取文件夹下所有文件
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Security.Cryptography; 6 using System.Text; 7 using System.Text.RegularExpressions; 8 using System.Threading.Tasks; 9 10 namespace DataManageBLL 11 { 12 public class FileHelper 13 { 14 ///// <summary> 15 ///// 遍历获取文件夹下所有文件 16 ///// </summary> 17 ///// <param name="fileFolder">要搜索的文件夹</param> 18 ///// <param name="allfiles">返回的文件列表</param> 19 //public static void GetAllFiles(string fileFolder, ref List<string> allfiles) 20 //{ 21 // DirectoryInfo Dir = new DirectoryInfo(fileFolder); 22 // FileInfo[] files = Dir.GetFiles(); 23 // foreach (var fileitem in files) 24 // { 25 // allfiles.Add(fileitem.FullName); 26 // } 27 // DirectoryInfo[] directorys = Dir.GetDirectories(); 28 // foreach (var directoryitem in directorys) 29 // { 30 // GetAllFiles(directoryitem.FullName, ref allfiles); 31 // } 32 //} 33 34 /// <summary> 35 /// 遍历获取文件夹下所有文件 36 /// </summary> 37 /// <param name="fileFolder">要搜索的文件夹</param> 38 /// <param name="allfiles">返回的文件列表</param> 39 public static void GetAllFiles(string fileFolder, ref List<string> allfiles, string ext = null, DateTime? startTime = null) 40 { 41 DateTime lastUploadDateTime = DateTime.MinValue; 42 GetAllFiles(fileFolder, ref allfiles, ref lastUploadDateTime, ext, startTime); 43 } 44 45 public static void GetAllFilesByImgPath(string decPath, ref List<string> allfiles, ref List<DateTime> lastUploadTimeList, string ext = null, DateTime? startTime = null) 46 { 47 DirectoryInfo Dir = new DirectoryInfo(decPath); 48 49 DirectoryInfo[] files = Dir.GetDirectories(); 50 if (files != null && files.Count() > 0) 51 { 52 if (!string.IsNullOrEmpty(ext)) 53 { 54 Regex regex = new Regex(ext); 55 files = files.Where(x => x.LastWriteTime > startTime).Where(x => regex.IsMatch(x.Name)).OrderBy(x => x.LastWriteTime).ToArray(); 56 } 57 else 58 files = files.Where(x => x.LastWriteTime > startTime).OrderBy(x => x.LastWriteTime).ToArray(); 59 60 if (startTime.HasValue) 61 { 62 foreach (var item in files) 63 { 64 allfiles.Add(item.FullName); 65 lastUploadTimeList.Add(item.LastWriteTime); 66 } 67 } 68 } 69 } 70 71 /// <summary> 72 /// 遍历获取文件夹下所有文件 73 /// </summary> 74 /// <param name="fileFolder">要搜索的文件夹</param> 75 /// <param name="allfiles">返回的文件列表</param> 76 public static void GetAllFiles(string fileFolder, ref List<string> allfiles, ref DateTime lastUploadTime, string ext = null, DateTime? startTime = null) 77 { 78 DirectoryInfo Dir = new DirectoryInfo(fileFolder); 79 80 FileInfo[] files = new FileInfo[] { }; 81 if (Dir.Exists) 82 files = Dir.GetFiles(); 83 foreach (var fileitem in files) 84 { 85 if (startTime == null || (startTime != null && fileitem.LastWriteTime < startTime.Value)) 86 { 87 if (string.IsNullOrEmpty(ext)) 88 { 89 allfiles.Add(fileitem.FullName); 90 if (lastUploadTime < fileitem.LastWriteTime) 91 { 92 lastUploadTime = fileitem.LastWriteTime; 93 } 94 } 95 else 96 { 97 string fileExt = Path.GetExtension(fileitem.FullName); 98 if (fileExt.ToLower() == ext.ToLower()) 99 { 100 allfiles.Add(fileitem.FullName); 101 if (lastUploadTime < fileitem.LastWriteTime) 102 { 103 lastUploadTime = fileitem.LastWriteTime; 104 } 105 } 106 } 107 } 108 } 109 DirectoryInfo[] directorys = Dir.GetDirectories(); 110 foreach (var directoryitem in directorys) 111 { 112 //if (startTime == null || (startTime != null && directoryitem.LastWriteTime < startTime.Value)) 113 GetAllFiles(directoryitem.FullName, ref allfiles, ref lastUploadTime, ext, startTime); 114 } 115 } 116 117 /// <summary> 118 /// 遍历获取文件夹下所有文件 119 /// </summary> 120 /// <param name="fileFolder">要搜索的文件夹</param> 121 /// <param name="allfiles">返回的文件列表</param> 122 public static void DeleteFiles(string fileFolder, ref List<string> allfiles, string ext = null, DateTime? startTime = null) 123 { 124 DateTime lastUploadDateTime = DateTime.MinValue; 125 DeleteFilesDetail(fileFolder, ref allfiles, ref lastUploadDateTime, ext, startTime); 126 } 127 128 129 /// <summary> 130 /// 遍历获取文件夹下所有文件 131 /// </summary> 132 /// <param name="fileFolder">要搜索的文件夹</param> 133 /// <param name="allfiles">返回的文件列表</param> 134 public static void DeleteFilesDetail(string fileFolder, ref List<string> allfiles, ref DateTime lastUploadTime, string ext = null, DateTime? startTime = null) 135 { 136 DirectoryInfo Dir = new DirectoryInfo(fileFolder); 137 138 FileInfo[] files = new FileInfo[] { }; 139 if (Dir.Exists) 140 files = Dir.GetFiles(); 141 foreach (var fileitem in files) 142 { 143 if (startTime == null || (startTime != null && fileitem.LastWriteTime < startTime.Value)) 144 { 145 try 146 { 147 File.Delete(fileitem.FullName); 148 } 149 catch (Exception ex) 150 { 151 continue; 152 } 153 } 154 } 155 DirectoryInfo[] directorys = Dir.GetDirectories(); 156 foreach (var directoryitem in directorys) 157 { 158 //if (startTime == null || (startTime != null && directoryitem.LastWriteTime < startTime.Value)) 159 DeleteFilesDetail(directoryitem.FullName, ref allfiles, ref lastUploadTime, ext, startTime); 160 } 161 } 162 163 164 public static void GetAllFilesByPath(string decPath, ref List<string> allfiles, ref List<DateTime> lastUploadTimeList, string ext = null, DateTime? startTime = null) 165 { 166 DirectoryInfo Dir = new DirectoryInfo(decPath); 167 168 FileInfo[] files = Dir.GetFiles(); 169 170 if (files != null && files.Count() > 0) 171 { 172 files = files.Where(x => x.LastWriteTime > startTime).ToArray(); 173 if (startTime.HasValue) 174 { 175 foreach (var item in files) 176 { 177 if (!string.IsNullOrEmpty(ext)) 178 { 179 if (item.Extension.ToLower() == ext.ToLower()) 180 { 181 allfiles.Add(item.FullName); 182 lastUploadTimeList.Add(item.LastWriteTime); 183 } 184 } 185 else if (string.IsNullOrEmpty(item.Extension)) 186 { 187 allfiles.Add(item.FullName); 188 lastUploadTimeList.Add(item.LastWriteTime); 189 } 190 } 191 } 192 } 193 194 DirectoryInfo[] fileDireS = Dir.GetDirectories(); 195 if (fileDireS != null && fileDireS.Count() > 0) 196 { 197 foreach (var item in fileDireS) 198 { 199 GetAllFilesByPath(item.FullName, ref allfiles, ref lastUploadTimeList, ext, startTime); 200 } 201 } 202 } 203 204 /// <summary> 205 /// 根据文件路径获取文件字节流 206 /// </summary> 207 /// <param name="filePath"></param> 208 /// <returns></returns> 209 public static byte[] GetFileToBytes(string filePath) 210 { 211 System.IO.Stream sm = GetFile(filePath); 212 byte[] buffer; 213 if (sm != null) 214 { 215 buffer = new byte[sm.Length]; 216 sm.Read(buffer, 0, (int)sm.Length); 217 sm.Close(); 218 219 return buffer; 220 } 221 return null; 222 } 223 224 /// <summary> 225 /// 根据文件路径获取文件流 226 /// </summary> 227 /// <param name="filePath"></param> 228 /// <returns></returns> 229 public static Stream GetFile(string filePath) 230 { 231 if (File.Exists(filePath)) 232 { 233 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); 234 return fs; 235 } 236 return null; 237 } 238 239 /// <summary> 240 /// 获取目录下的所有子目录 241 /// </summary> 242 /// <param name="fileFolder"></param> 243 /// <returns></returns> 244 public static List<string> GetAllDirectorys(string fileFolder, DateTime? startTime = null) 245 { 246 if (!Directory.Exists(fileFolder)) 247 { 248 //路径不存在 249 return null; 250 } 251 DirectoryInfo Dir = new DirectoryInfo(fileFolder); 252 if (startTime == null) 253 return Dir.GetDirectories().Select(i => i.FullName).ToList(); 254 else 255 return Dir.GetDirectories().Where(i => i.CreationTime <= startTime).Select(i => i.FullName).ToList(); 256 } 257 258 /// <summary> 259 /// 获取文件的MD5哈希值 260 /// </summary> 261 /// <param name="filePath">文件名</param> 262 /// <returns></returns> 263 public static string GetFileMD5Hash(string filePath) 264 { 265 FileStream get_file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); 266 MD5CryptoServiceProvider get_md5 = new MD5CryptoServiceProvider(); 267 byte[] hash_byte = get_md5.ComputeHash(get_file); 268 get_file.Close(); 269 string result = BitConverter.ToString(hash_byte); 270 return result.Replace("-", ""); 271 } 272 273 /// <summary> 274 /// 获取某个流的MD5值 275 /// 注:流必须先seek(0,begin) 276 /// </summary> 277 /// <param name="stream"></param> 278 /// <returns></returns> 279 public static string GetStreamMD5Hash(Stream stream) 280 { 281 MD5CryptoServiceProvider get_md5 = new MD5CryptoServiceProvider(); 282 byte[] hash_byte = get_md5.ComputeHash(stream); 283 string result = BitConverter.ToString(hash_byte); 284 return result.Replace("-", ""); 285 } 286 287 /// <summary> 288 /// 删除文件 289 /// </summary> 290 /// <param name="filePath"></param> 291 public static void FileDelete(string filePath) 292 { 293 if (File.Exists(filePath)) 294 { 295 File.Delete(filePath); 296 } 297 } 298 299 /// <summary> 300 /// 移动文件(多个) 301 /// </summary> 302 /// <param name="srcFileFullPathes">源文件(数组)</param> 303 /// <param name="destFileSubPathes">目标文件(数组)</param> 304 /// <param name="isOverwrite">是否覆盖</param> 305 /// <returns> 306 /// 拷贝后文件的全路径 307 /// </returns> 308 public static void Move(string[] srcFileFullPathes, string[] destFileFullPathes, bool isOverwrite) 309 { 310 //参数检查 311 if (srcFileFullPathes.Length != destFileFullPathes.Length) 312 { 313 throw new Exception("[源文件个数]与[目标文件个数]不匹配!"); 314 } 315 //检查目标路径是否存在,不存在就创建 316 for (int i = 0; i < destFileFullPathes.Length; i++) 317 { 318 //路径相同不检查目录 319 if (string.Compare(srcFileFullPathes[i], destFileFullPathes[i]) == 0) 320 { 321 continue; 322 } 323 //检查目标文件目录 324 CheckDirectory(destFileFullPathes[i]); 325 } 326 try 327 { 328 for (int i = 0; i < srcFileFullPathes.Length; i++) 329 { 330 //路径相同不移动 331 if (string.Compare(srcFileFullPathes[i], destFileFullPathes[i]) == 0) continue; 332 333 if (!File.Exists(destFileFullPathes[i])) 334 { 335 //移动文件 336 File.Move(srcFileFullPathes[i], destFileFullPathes[i]); 337 } 338 else if (isOverwrite) 339 { //覆盖 340 File.Delete(destFileFullPathes[i]); 341 342 File.Move(srcFileFullPathes[i], destFileFullPathes[i]); 343 } 344 } 345 } 346 catch (Exception ex) 347 { 348 throw; 349 } 350 } 351 352 /// <summary> 353 /// 检查目录是否存在,不存在就创建目录 354 /// </summary> 355 /// <param name="filePath"></param> 356 public static void CheckDirectory(string filePath) 357 { 358 string directory = filePath.Substring(0, filePath.LastIndexOf(@"\")); 359 if (!Directory.Exists(directory)) 360 { 361 try 362 { 363 Directory.CreateDirectory(directory); 364 } 365 catch (Exception ex) 366 { 367 throw; 368 } 369 } 370 371 } 372 373 /// <summary> 374 /// 将A文件夹里面的文件和文件夹移动到B文件夹 375 /// </summary> 376 /// <param name="sourcedirectory"></param> 377 /// <param name="destinationdirectory"></param> 378 public static void FolderMoveToNewFolder(string sourcedirectory, string destinationdirectory) 379 { 380 try 381 { 382 DirectoryInfo nowFolder = new DirectoryInfo(sourcedirectory); 383 destinationdirectory = Path.Combine(destinationdirectory, nowFolder.Name); 384 385 if (!Directory.Exists(destinationdirectory)) 386 Directory.CreateDirectory(destinationdirectory); 387 388 string[] fileList = Directory.GetFileSystemEntries(sourcedirectory); 389 foreach (string file in fileList) 390 { 391 if (Directory.Exists(destinationdirectory)) 392 { 393 //Directory.Move(file, destinationdirectory); 394 DirectoryInfo folder = new DirectoryInfo(file); 395 string strCreateFileName = destinationdirectory + "\\" + folder.Name; 396 if (!Directory.Exists(strCreateFileName)) 397 folder.MoveTo(strCreateFileName); 398 else 399 folder.Delete(); 400 } 401 else 402 Directory.Move(sourcedirectory, destinationdirectory); 403 404 405 406 if (File.Exists(file)) 407 { 408 File.Move(file, destinationdirectory); 409 //FileInfo fi = new FileInfo(file); 410 //fi.MoveTo(newFolderPath); 411 } 412 } 413 } 414 catch (Exception ex) 415 { 416 } 417 } 418 } 419 }
我一般使用“GetAllFiles”,“DeleteFiles”方法。可以自行决定用哪一个方法