2012-06-07 30 views
4

我試圖從源文件夾複製所有格式文件(.txt,.pdf,.doc ...)文件到目的地。從c#中的文件夾複製所有類型的格式文件

我只寫文本文件的代碼。

我應該怎麼做才能複製所有格式文件?

我的代碼:

string fileName = "test.txt"; 
string sourcePath = @"E:\test222"; 
string targetPath = @"E:\TestFolder"; 

string sourceFile = System.IO.Path.Combine(sourcePath, fileName); 
string destFile = System.IO.Path.Combine(targetPath, fileName); 

代碼複製文件:通過

System.IO.File.Copy(sourceFile, destFile, true); 
+0

可能的複製(http://stackoverflow.com/questions/677221/copy-folders-in-c-sharp-using-system-io) –

回答

10

使用Directory.GetFiles和循環路徑

string sourcePath = @"E:\test222"; 
string targetPath = @"E:\TestFolder"; 

foreach (var sourceFilePath in Directory.GetFiles(sourcePath)) 
{ 
    string fileName = Path.GetFileName(sourceFilePath); 
    string destinationFilePath = Path.Combine(targetPath, fileName); 

    System.IO.File.Copy(sourceFilePath, destinationFilePath , true); 
} 
+0

誰這是什麼東西? –

+1

這個答案爲什麼被拒絕? –

+0

不知道,如果你不同意,請將它備份! :) –

2
string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories); 

使用這種和循環所有文件複製到目標文件夾

2

我有點印象,你想擴展過濾。如果是這樣,這將做到這一點。如果你不這樣做,請註釋下面指出的部分。

string sourcePath = @"E:\test222"; 
string targetPath = @"E:\TestFolder"; 

var extensions = new[] {".txt", ".pdf", ".doc" }; // not sure if you really wanted to filter by extension or not, it kinda seemed like maybe you did. if not, comment this out 

var files = (from file in Directory.EnumerateFiles(sourcePath) 
      where extensions.Contains(Path.GetExtension(file), StringComparer.InvariantCultureIgnoreCase) // comment this out if you don't want to filter extensions 
      select new 
          { 
           Source = file, 
           Destination = Path.Combine(targetPath, Path.GetFileName(file)) 
          }); 

foreach(var file in files) 
{ 
    File.Copy(file.Source, file.Destination); 
} 
[使用C#中複製文件夾System.IO]的
+0

哈哈複製粘貼你自己的代碼:) –

相關問題