在複製整個目錄的同時,更重要的是我們要複製其子目錄和相關檔案。
讓我們考慮以下範例來源目錄,其中包含子目錄和檔案。
下面是範例目標目錄,最初為空。
using System; using System.IO; namespace DemoApplication { class Program { public static void Main() { string sourceDirectory = @"d:\DemoSourceDirectory"; string targetDirectory = @"d:\DemoTargetDirectory"; DirectoryInfo sourceDircetory = new DirectoryInfo(sourceDirectory); DirectoryInfo targetDircetory = new DirectoryInfo(targetDirectory); CopyAll(sourceDircetory, targetDircetory); Console.ReadLine(); } public static void CopyAll(DirectoryInfo source, DirectoryInfo target) { Directory.CreateDirectory(target.FullName); foreach (FileInfo fi in source.GetFiles()) { Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name); fi.CopyTo(Path.Combine(target.FullName, fi.Name), true); } foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name); CopyAll(diSourceSubDir, nextTargetSubDir); } } } }
#以上程式碼的輸出結果為
##
以上是如何在C#中複製目錄的全部內容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!