2016-02-24 24 views
0

我看着System.IO.File.Move,將文件「移動」到一個新的名字。在C#中遞歸複製文件夾,反正有嗎?

System.IO.File.Move("oldfilename", "newfilename"); 

但是這對我來說不足以使用這種方法。

Infact我想遞歸地將一個文件夾及其所有子文件夾複製到一個新路徑中,並更改這些文件的名稱。任何人都可以帶我一段代碼?

+0

要循環每個子目錄更安全,遞歸,相關主題:HTTP://計算器.com/questions/34525090/access-to-the-path-d-recycle-bin-s-1-5-21-494745725-312220573-749543506-41600/34525432#34525432 – Ian

+0

這是非常相似的,但不會改變文件的名稱:http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c- sharp –

回答

1

如果要移動的文件夾:

string newDirPath = "E:\\New\\destDirName"; 
Directory.CreateDirectory(newDirPath); 
Directory.Move("D:\\sourceDirPath", newDirPath); 

如果你想copy a folder

//Create all of the directories 
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", 
    SearchOption.AllDirectories)) 
    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); 

//Copy all the files & Replaces any files with the same name 
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", 
    SearchOption.AllDirectories)) 
    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true); 
+1

來源:http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c-sharp –

+0

使用此命令我們可以訪問所有文件夾和子文件夾「foreach(Directory.GetDirectories(SourcePath,」*「, SearchOption.AllDirectories)中的字符串dirPath)」okey? –

+0

@MathLover是的。 – Sakura