如何在 C# 中将文件复制到目录中?
为了复制文件,C# 提供一个方法File.Copy
File.Copy 有 2 个重载
Copy(String, String) -将现有文件复制到新文件中。不允许覆盖同名文件。
Copy(String, String, Boolean) 将现有文件复制到新文件中。允许覆盖同名文件。
Directory.GetFiles 返回与指定搜索模式匹配的所有文件(包括其路径)的名称,还可以搜索子目录。
示例
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1"; var searchSourceFolder = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly); Console.WriteLine("-------------Source Folder-------------"); foreach (string file in searchSourceFolder){ Console.WriteLine(file); } string destinationFolder = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\"; var destinationFolderFiles = Directory.GetFiles(destinationFolder, "*.*", SearchOption.TopDirectoryOnly); Console.WriteLine("-------------Destination Folder Before Copying-------------"); foreach (string file in destinationFolderFiles){ Console.WriteLine(file); } string[] files = Directory.GetFiles(rootPath); foreach (string file in files){ File.Copy(file, $"{destinationFolder}{ Path.GetFileName(file) }"); } Console.WriteLine("-------------After Copying-------------"); var destinationFolderAfterCopyingFiles = Directory.GetFiles(destinationFolder, "*.*", SearchOption.TopDirectoryOnly); foreach (string file in destinationFolderAfterCopyingFiles){ Console.WriteLine(file); } Console.ReadLine (); }
输出
-------------Source Folder------------- C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1\TestFolderMain1.txt -------------Destination Folder Before Copying------------- C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt -------------After Copying------------- C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain1.txt C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt
广告