2013-03-18 115 views
-4

請讓我知道如何將文件夾中的所有文件複製到c#.net中的另一個文件夾中。如何將文件夾中的所有文件複製到c中的另一個文件夾中#

目前我使用:

int j = 1; 
int k = 1; 

    for (j = 1; j < 5; j++) 
    { 

     for (k = 1; k < 32; k++) 
     { 

      string sourcePath = @Desktop_location + "\Test" + k + ".log"; 

      if (System.IO.File.Exists(sourcePath)) 
      { 
       File.Copy(@Desktop_location + "\\Statistics\\Server" + j + "\Test" + k + ".log", @Desktop_location + "\\Statistics\\Transfer\\test" + j + k + ".log"); 
       //Console.WriteLine("Test Result"); 
      } 
      else 
      { 
       //Console.WriteLine("Test"); 
+2

能完成這項工作?你想以某種方式改進它嗎? – Jodrell 2013-03-18 11:25:05

+0

請別人幫助我如何將多個文件夾中的所有文件複製到一個文件夾中。另外,請建議如果具有相同名稱的文件存在於多個文件夾中,但它的區別是不同的。 – Dorgy 2013-03-18 11:25:45

+3

這些魔術數字'5'和'32'是什麼? – TalentTuner 2013-03-18 11:25:46

回答

0

如果你真的想複製所有文件,你可以做這樣的(副本的所有內容,包括目錄):

foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) 
{ 
    Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath)); 
} 

foreach (var newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) 
{ 
    File.Copy(newPath, newPath.Replace(sourcePath, destinationPath)); 
} 
+0

以及請建議如果具有相同名稱的文件存在於多個文件夾中,但我想保留這兩個文件夾中的文件,我正在複製這些文件 – Dorgy 2013-03-18 11:37:41

+0

@GulshanAnand這是初學者邏輯,請儘量自己編寫代碼。你永遠不會學習複製和粘貼其他人的代碼。 – Amicable 2013-03-18 11:44:06

+0

取決於您希望如何命名這些重複項。你是否喜歡Explorer使用的命名約定,即它會在文件名的後面加上「(1)」後綴? – 2013-03-18 11:44:30

1
string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); 

Getting files from a directory

string myPath = @"C:\Test"; 
foreach (string file in filePaths) 
{ 
    FileInfo info = new FileInfo(file); 
    if (!File.Exists(info.FullName)) 
    { 
     File.Copy(info.FullName, newPath); 
    } 
} 

請參閱Using FileInfo Class,您實際上並不需要它,但它包含許多用於處理文件和文件夾的有用功能。 閱讀它將幫助你規劃你的應用程序。

+0

只有一個文件正在使用此代碼進行復制。請幫助: – Dorgy 2013-03-18 11:49:23

+0

@GulshanAnand你正在努力工作,只是要求我爲你做,所以我不再非常樂意幫助你。 這對初學者來說應該很容易解決。如果您不知道如何調試閱讀[this](http://www.codeproject.com/Articles/79508/Mastering-Debugging-in-Visual-Studio-2010-A-Beginn)文章。 – Amicable 2013-03-18 11:53:14

相關問題