簡體   English   中英

如何將多個文件夾復制到另一個文件夾?

[英]How to copy more than one folder into another folder?

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

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

這是迄今為止的代碼。 (有些來自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.我選擇目標文件夾。 我按OK。 預期結果:目標文件夾有兩個文件夾,文件夾1和文件夾2。 兩者都包含所有文件。 實際結果:目標文件夾合並了松散文件,源文件夾的子目錄完好無損。 (這是什么煩人的)

我希望這對你的專業人士來說是足夠的信息。

問題是你永遠不會為你的目的地創建一個新目標 - 這將為循環的每次迭代創建一個與源名稱相同的新目標,然后復制到該目標。

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);                
 }

警告我沒有測試,所以我可能有錯字,但你明白了。

而不是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);
        }
    }
}

在主要功能。

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)
        }
    }

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

            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");

這將幫助您解決您的問題。此功能是復制文件夾的通用遞歸功能,包含或不包含合並的子文件夾。

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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM