如何将多个文件夹复制到另一个文件夹中

本文关键字:文件夹 复制 另一个 | 更新日期: 2023-09-27 18:36:04

现在问题来了:我有很多代码都做同样的事情。也就是说,它将两个文件夹的内容复制到目标文件夹中,并将它们合并到目标文件夹中。我的问题是,我无法找出(经过大量谷歌搜索)如何实际复制源目录+内容,而不仅仅是其内容和最终合并的子文件夹。

这可能是我获取目录的方式:我使用文件夹选择对话框,将路径名添加到列表框(要显示),然后从列表框中的项目创建(字符串)目录列表。

这是到目前为止的代码。(部分来自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。我选择目标文件夹。我按确定。预期结果: 目标文件夹有两个文件夹,文件夹 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);
        }
    }
}