将文件夹中的所有内容复制到两个文件目标文件夹中

时间:2017-05-27 07:13:15

标签: c#

我想将文件夹中的所有内容复制到两个文件目标文件夹中。

   foreach (string newPath in Directory.GetFiles(@"E:\autotransfer", "*.*",
            SearchOption.AllDirectories))
            File.Copy(newPath, newPath.Replace(@"E:\autotransfer", 
   @"E:\autotransferbackup"), true);

   foreach (string newPath in Directory.GetFiles(@"E:\autotransfer", "*.*",
            SearchOption.AllDirectories))
            File.Copy(newPath, newPath.Replace(@"E:\autotransfer", 
   @"E:\autotransferbackupcp"), true); 

2 个答案:

答案 0 :(得分:0)

您可以使用此代码,有关详细信息,请参阅此处的答案:Copy all files in directory

    void Copy(string sourceDir, string targetDir)
    {
        Directory.CreateDirectory(targetDir);

        foreach (var file in Directory.GetFiles(sourceDir))
            File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));

        foreach (var directory in Directory.GetDirectories(sourceDir))
            Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Copy("E:\autotransfer", "E:\autotransferbackup");
        Copy("E:\autotransfer", "E:\autotransferbackupcp");
    }

如果目录结构不相同,则需要检查文件夹是否存在,如果不存在,请先创建,然后复制文件。

答案 1 :(得分:0)

取自msdn:https://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx

您可以复制此功能并在代码中使用它。

希望这有帮助。

using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        // Copy from the current directory, include subdirectories.
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);

        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        DirectoryInfo[] dirs = dir.GetDirectories();
        // 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 = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}