如何将文件复制到C#目录中?
要复制文件,C#提供了一种方法File。复制
文件。副本有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