2013-10-20 139 views
3

現在是這個問題: 我有很多代碼都做同樣的事情。也就是說,它將兩個文件夾的內容複製到目標文件夾中,並將它們合併到目標文件夾中。我的問題是,我找不到(經過很多谷歌搜索)如何實際複製源目錄+內容而不僅僅是其內容和子文件夾然後最終合併如何將多個文件夾複製到另一個文件夾?

這可能是我如何獲取目錄:我使用文件夾選擇對話框,將路徑名添加到列表框(要顯示),然後從列表框中的項目創建(字符串)目錄列表。

這是目前爲止的代碼。 (有些來自MSDN)

public static void CopyAll(DirectoryInfo source, DirectoryInfo target) 
    { 
     if (source.FullName.ToLower() == target.FullName.ToLower()) 
     { 
      return; 
     } 

     // Check if the target directory exists, if not, create it. 
     if (Directory.Exists(target.FullName) == false) 
     { 
      Directory.CreateDirectory(target.FullName); 
     } 

     // Copy each file into it's new directory. 
     foreach (FileInfo fi in source.GetFiles()) 
     { 
      fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true); 
     } 

     // Copy each subdirectory using recursion. 
     foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) 
     { 
      DirectoryInfo nextTargetSubDir = 
       target.CreateSubdirectory(diSourceSubDir.Name); 
      CopyAll(diSourceSubDir, nextTargetSubDir); 
     } 
    } 
    //This is inside a button click Method 

    List<string> pathList = new List<string>(); 
     pathList = lstBox.Items.Cast<String>().ToList(); 

     string sourceDirectory; 
     string targetDirectory; 

     DirectoryInfo dirSource; 
     DirectoryInfo dirTarget; 

     for (int i = 0 ; i < pathList.Count; i++) 
     { 
      sourceDirectory = pathList.ElementAt(i); 
      targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog 
      dirSource = new DirectoryInfo(sourceDirectory); 
      dirTarget = new DirectoryInfo(targetDirectory); 

      CopyAll(dirSource, dirTarget);     
     } 

煩人的C#沒有Directory.Copy函數,這將是非常有用的。 重述。

我選擇文件夾1. 我選擇文件夾2. 我選擇目的地文件夾。 I按OK。 預期結果:目標文件夾內有兩個文件夾,即文件夾1和文件夾2。兩者都有裏面的所有文件。 實際結果:目標文件夾合併了鬆散文件,並且源文件夾的子目錄完好無損。 (這是什麼煩人)

我希望這是足夠的信息,爲您的專業人士提供幫助。

+2

如果您的函數將兩個String對象(源和目標路徑)作爲參數,則更簡潔的方法是。檢查接受答案在這裏:http://stackoverflow.com/questions/1066674/how-do-i-copy-a-folder-and-all-subfolders-and-files-in-net/1066707#1066707 – tpolyak

+0

我已經做了更多的搜索,甚至添加了對Visual Basic DLL的引用 - 它有自己的CopyDirectory()方法。它完全一樣的問題。問題必須在於我如何獲取源目錄或其他內容。不知道...謝謝! – Sizza

+1

@Sizza - 是的,這是你如何打電話給副本 - 看到我的答案。 – Hogan

回答

1

的問題是你永遠做一個新的目標,你的目的地 - 這將使新的目標具有相同名稱的來源爲循環的每個迭代,然後複製到目標。

for (int i = 0 ; i < pathList.Count; i++) 
{ 
    sourceDirectory = pathList.ElementAt(i); 
    targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog 
    dirSource = new DirectoryInfo(sourceDirectory); 

    string targetPath = target.Fullname+ 
        Path.DirectorySeparatorChar+ 
        sourceDirectory.Split(Path.DirectorySeparatorChar).Last()); 

    Directory.CreateDirectory(targetPath); 

    dirTarget = new DirectoryInfo(targetPath); 

    CopyAll(dirSource, dirTarget);     
} 

警告我沒有測試,所以我可能有錯別字,但你的想法。

+0

啊哈,這就是我的想法。我想這可能是發佈後的問題。謝謝,我現在要測試它。 – Sizza

+0

對,所以我在Button Method中測試了這個。它什麼都不做。 (這是一種進步)。也許我需要在複製方法本身中創建新的目標? – Sizza

+1

@Sizza - 這確實創建了目標...它說創建目錄的地方 - 在調試器中運行並查看變量是什麼。也許browserSave.SelectedPath沒有設置? – Hogan

0

而不是DirectoryInfo通過string作爲參數。請參閱下面的代碼。

private void DirectoryCopy(
    string sourceDirName, string destDirName, bool copySubDirs) 
{ 
    DirectoryInfo dir = new DirectoryInfo(sourceDirName); 
    DirectoryInfo[] dirs = dir.GetDirectories(); 

    // If the source directory does not exist, throw an exception. 
    if (!dir.Exists) 
    { 
     throw new DirectoryNotFoundException(
      "Source directory does not exist or could not be found: " 
      + sourceDirName); 
    } 

    // If the destination directory does not exist, create it. 
    if (!Directory.Exists(destDirName)) 
    { 
     Directory.CreateDirectory(destDirName); 
    } 


    // Get the file contents of the directory to copy. 
    FileInfo[] files = dir.GetFiles(); 

    foreach (FileInfo file in files) 
    { 
     // Create the path to the new copy of the file. 
     string temppath = Path.Combine(destDirName, file.Name); 

     // Copy the file. 
     file.CopyTo(temppath, false); 
    } 

    // If copySubDirs is true, copy the subdirectories. 
    if (copySubDirs) 
    { 

     foreach (DirectoryInfo subdir in dirs) 
     { 
      // Create the subdirectory. 
      string temppath = Path.Combine(destDirName, subdir.Name); 

      // Copy the subdirectories. 
      DirectoryCopy(subdir.FullName, temppath, copySubDirs); 
     } 
    } 
} 

在main函數中。

static void Main(string[] args) 
    { 

     List<string> directoryNames = new List<string>() // For multiple source folders 
     { 
      "C:\\Folder1", "C:\\Folder2" 
     }; 

     string destDirName = "C:\\Folder3"; 
     foreach (string sourceDirName in directoryNames) 
     { 
      DirectoryCopy(sourceDirName, destDirName, true) 
     } 
    } 
+0

我已經使用了這個代碼,它有同樣的問題:( – Sizza

+0

我已經使用這段代碼,它會將所有的源目錄,子目錄和文件複製到目標文件夾中,實際上問題出在哪裏? –

+0

我明白代碼的作用,我需要做的是將源文件夾+內容複製到我選擇的一個新文件夾中。我剛剛嘗試過的代碼的功能是將源文件夾的內容複製到目標文件夾中。當我選擇多個文件夾進行復制時,它會合並它們,我希望保留樹結構 – Sizza

-1

這將幫助你解決你的問題。這個功能是一個通用的遞歸函數複製文件夾與或不合並子文件夾。

public static void DirectoryCopy(string sourceDirPath, string destDirName, bool isCopySubDirs) 
{ 
    // Get the subdirectories for the specified directory. 
    DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirPath); 
    DirectoryInfo[] directories = directoryInfo.GetDirectories(); 
    if (!directoryInfo.Exists) 
    { 
     throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " 
      + sourceDirPath); 
    } 
    DirectoryInfo parentDirectory = Directory.GetParent(directoryInfo.FullName); 
    destDirName = System.IO.Path.Combine(parentDirectory.FullName, destDirName); 

    // If the destination directory doesn't exist, create it. 
    if (!Directory.Exists(destDirName)) 
    { 
     Directory.CreateDirectory(destDirName); 
    } 
    // Get the files in the directory and copy them to the new location. 
    FileInfo[] files = directoryInfo.GetFiles(); 

    foreach (FileInfo file in files) 
    { 
     string tempPath = System.IO.Path.Combine(destDirName, file.Name); 

     if (File.Exists(tempPath)) 
     { 
      File.Delete(tempPath); 
     } 

     file.CopyTo(tempPath, false); 
    } 
    // If copying subdirectories, copy them and their contents to new location using recursive function. 
    if (isCopySubDirs) 
    { 
     foreach (DirectoryInfo item in directories) 
     { 
      string tempPath = System.IO.Path.Combine(destDirName, item.Name); 
      DirectoryCopy(item.FullName, tempPath, isCopySubDirs); 
     } 
    } 
} 
+1

複製例程不是問題 – Hogan

0

請嘗試以下操作。您顯然需要在調用操作時相應地設置源文件夾和目標文件夾。此外,我會建議你不要在事件處理程序中嵌入任何邏輯。 希望這有助於。

  Action<string, string> action = null; 
      action = (source,dest) => 
       { 
        if(Directory.Exists(source)) 
        { 
         DirectoryInfo sInfo = new DirectoryInfo(source); 
         if (!Directory.Exists(dest)) 
         { 
          Directory.CreateDirectory(dest); 
         } 
         Array.ForEach(sInfo.GetFiles("*"), a => File.Copy(a.FullName, Path.Combine(dest,a.Name))); 
         foreach (string dir in Directory.EnumerateDirectories(source)) 
         { 
          string sSubDirPath = dir.Substring(source.Length+1,dir.Length-source.Length-1); 
          string dSubDirPath = Path.Combine(dest,sSubDirPath); 
          action(dir, dSubDirPath); 
         } 
        } 
       }; 
      action(@"C:\source", @"C:\dest"); 
相關問題