1. 程式人生 > 實用技巧 >c# 遞迴獲取所有目錄,所有檔案,並替換檔案

c# 遞迴獲取所有目錄,所有檔案,並替換檔案

//獲取所有檔案
private
static void GetFileList(DirectoryInfo dir, List<FileInfo> fileList) { fileList.AddRange(dir.GetFiles()); foreach (DirectoryInfo directory in dir.GetDirectories()) GetFileList(directory, fileList); }
//獲取所有目錄
private static void GetDirList(DirectoryInfo dir, List<DirectoryInfo> dirList) { dirList.AddRange(dir.GetDirectories());
foreach (DirectoryInfo directory in dir.GetDirectories()) GetDirList(directory, dirList); } public static void CopyDireToDire(string sourceDire, string destDire, string backupsDire) { if (!Directory.Exists(destDire)) { Directory.CreateDirectory(destDire); } if
(!Directory.Exists(backupsDire)) { Directory.CreateDirectory(backupsDire); } DirectoryInfo sourceDireInfo = new DirectoryInfo(sourceDire); List<FileInfo> fileList = new List<FileInfo>(); GetFileList(sourceDireInfo, fileList); List<DirectoryInfo> dirList = new
List<DirectoryInfo>(); GetDirList(sourceDireInfo, dirList);
//新增不存在目錄
foreach (DirectoryInfo dir in dirList) { string m = dir.FullName; string n = m.Replace(sourceDire, destDire); if (!Directory.Exists(n)) { Directory.CreateDirectory(n); } string o = m.Replace(sourceDire, backupsDire); if (!Directory.Exists(o)) { Directory.CreateDirectory(o); } }
//替換檔案,並備份
foreach (FileInfo fileInfo in fileList) { string sourceFile = fileInfo.FullName; string destFile = sourceFile.Replace(sourceDire, destDire); if (File.Exists(destFile)) { string backFile = destFile.Replace(destDire, backupsDire); File.Copy(destFile, backFile, true); } File.Copy(sourceFile, destFile, true); } }

部分參考其他的,