Copy the entire contents of a directory in C#

前端 未结 22 824
日久生厌
日久生厌 2020-11-22 07:13

I want to copy the entire contents of a directory from one location to another in C#.

There doesn\'t appear to be a way to do this using System.IO class

相关标签:
22条回答
  • 2020-11-22 07:21

    Much easier

    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", 
        SearchOption.AllDirectories))
        Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
    
    //Copy all the files & Replaces any files with the same name
    foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", 
        SearchOption.AllDirectories))
        File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
    
    0 讨论(0)
  • 2020-11-22 07:24

    If you like Konrad's popular answer, but you want the source itself to be a folder under target, rather than putting it's children under the target folder, here's the code for that. It returns the newly created DirectoryInfo, which is handy:

    public static DirectoryInfo CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
    {
      var newDirectoryInfo = target.CreateSubdirectory(source.Name);
      foreach (var fileInfo in source.GetFiles())
        fileInfo.CopyTo(Path.Combine(newDirectoryInfo.FullName, fileInfo.Name));
    
      foreach (var childDirectoryInfo in source.GetDirectories())
        CopyFilesRecursively(childDirectoryInfo, newDirectoryInfo);
    
      return newDirectoryInfo;
    }
    
    0 讨论(0)
  • 2020-11-22 07:27

    One variant with only one loop for copying of all folders and files:

    foreach (var f in Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories))
    {
        var output = Regex.Replace(f, @"^" + path, newPath);
        if (File.Exists(f)) File.Copy(f, output, true);
        else Directory.CreateDirectory(output);
    }
    
    0 讨论(0)
  • 2020-11-22 07:29

    It may not be performance-aware, but I'm using it for 30MB folders and it works flawlessly. Plus, I didn't like all the amount of code and recursion required for such an easy task.

    var src = "c:\src";
    var dest = "c:\dest";
    var cmp = CompressionLevel.NoCompression;
    var zip = source_folder + ".zip";
    
    ZipFile.CreateFromDirectory(src, zip, cmp, includeBaseDirectory: false);
    ZipFile.ExtractToDirectory(zip, dest_folder);
    
    File.Delete(zip);
    

    Note: ZipFile is available on .NET 4.5+ in the System.IO.Compression namespace

    0 讨论(0)
  • 2020-11-22 07:30

    You can always use this, taken from Microsofts website.

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:31

    Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:

    Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);
    

    However, using one of the recursive functions is a better way to go since it won't have to load the VB dll.

    0 讨论(0)
提交回复
热议问题