2012-09-13 51 views
1

我想要的是我的USB驅動器I:/上的一些文件,目錄和子目錄的精確副本,並希望他們在C:/backup(例如)如何將文件從一個磁盤複製到具有相同文件夾結構的另一個位置?

我的USB驅動器具有以下結構:

(只知道,這是一個例子,我的驅動器有多個文件,目錄和子目錄)

  • 課程/ data_structures/db.sql

  • 遊戲/ PC/PC-的Game.exe

  • 考試/ exam01.doc


好了,我不知道如何開始,但我的第一個想法是讓所有的files這樣做:

string[] files = Directory.GetFiles("I:"); 

下一步可能是做一個循環,並使用File.Copy指定目標路徑:

string destinationPath = @"C:/backup"; 

foreach (string file in files) 
{ 
    File.Copy(file, destinationPath + "\\" + Path.GetFileName(file), true); 
} 

此時一切工作不錯,但不是因爲我想造成這種不復制的文件夾結構。也有一些錯誤發生類似下面...

  • 第一個是因爲我的電腦配置顯示隱藏文件的每個文件夾和我的USB有沒有隱藏了一個AUTORUN.INF隱藏文件和環路試圖複製並在此過程生成此異常:

訪問路徑「AUTORUN.INF」被拒絕。

  • 第二個發生在某些路徑太長,這會產生以下例外:

指定的路徑,文件名,或兩者均爲太長。完整 限定文件名必須少於260個字符,並且 目錄名稱必須少於248個字符。


所以,我不知道如何實現這一點,並驗證錯誤的每個更多鈔票的情況。我想知道是否有另一種方式來做到這一點,如何(也許有些庫)或一些更簡單的像與以下結構的實現方法:

File.CopyDrive(driveLetter, destinationFolder)

(VB。NET答案也會被接受)。

在此先感謝。

回答

3
public static void Copy(string src, string dest) 
{ 
    // copy all files 
    foreach (string file in Directory.GetFiles(src)) 
    { 
     try 
     { 
      File.Copy(file, Path.Combine(dest, Path.GetFileName(file))); 
     } 
     catch (PathTooLongException) 
     { 
     } 
     // catch any other exception that you want. 
     // List of possible exceptions here: http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx 
    } 

    // go recursive on directories 
    foreach (string dir in Directory.GetDirectories(src)) 
    { 

     // First create directory... 
     // Instead of new DirectoryInfo(dir).Name, you can use any other way to get the dir name, 
     // but not Path.GetDirectoryName, since it returns full dir name. 
     string destSubDir = Path.Combine(dest, new DirectoryInfo(dir).Name); 
     Directory.CreateDirectory(destSubDir); 
     // and then go recursive 
     Copy(dir, destSubDir); 
    } 
} 

然後你就可以把它叫做:

Copy(@"I:\", @"C:\Backup"); 

沒有時間來測試它,但我希望你的想法...

編輯:在上面的代碼中,有像Directory.Exists並沒有這樣的檢查,你可能會如果某種目錄結構存在於目標路徑添加這些。如果你想創建某種簡單的同步應用程序,那麼它變得有點困難,因爲你需要刪除或採取上的文件/文件夾不存在了其他行動。

0

你可能要考慮超載CopyDirectory

CopyDirectory(String, String, UIOption, UICancelOption) 

它將通過所有子目錄的遞歸。

如果你想有一個獨立的應用程序,我寫了一個應用程序,從一個選定的目錄複製到另一個,覆蓋較新的文件,並根據需要添加子目錄。

只是給我發電子郵件。

相關問題