如何递归复制.Net中的文件夹?

时间:2014-11-08 09:44:55

标签: c# .net

我有以下脚本,它使用一个源文件夹并使用FileStream文件复制到另一个文件夹。

我需要以递归方式获取任何子文件夹并复制其文件的方式进行更改。

如何修改方法?

- source folder
  - file
  - file
  - folder
     - file
     - file
     - folder
       - file
  - folder
     - file
     - file
     - folder
       - file





 public static void SynchFolders()
    {
        DirectoryInfo StartDirectory = new DirectoryInfo(SourceUNC);
        DirectoryInfo EndDirectory = new DirectoryInfo(TargetUNC);

        foreach (FileInfo file in StartDirectory.EnumerateFiles())
        {
            using (FileStream SourceStream = file.OpenRead())
            {
                string dirPath = StartDirectory.FullName;
                string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
                using (FileStream DestinationStream = File.Create(outputPath + "\\" + file.Name))
                {
                    SourceStream.CopyToAsync(DestinationStream);
                }
            }
        }
    }

3 个答案:

答案 0 :(得分:2)

基本上您需要做的是稍微扩展您的功能,以便在复制特定目录中找到的所有文件后,它将搜索当前文件夹中的子文件夹并递归到该文件夹​​,以便执行相同的过程在每个子文件夹上。

基于原始代码的示例函数:

 public static void SynchFolders(string SourceUNC, string TargetUNC)
    {
        DirectoryInfo StartDirectory = new DirectoryInfo(SourceUNC);
        DirectoryInfo EndDirectory = new DirectoryInfo(TargetUNC);

        // Copy Files
        foreach (FileInfo file in StartDirectory.EnumerateFiles())
        {
            using (FileStream SourceStream = file.OpenRead())
            {
                string dirPath = StartDirectory.FullName;
                string outputPath = dirPath.Replace(StartDirectory.FullName, EndDirectory.FullName);
                using (FileStream DestinationStream = File.Create(outputPath + "\\" + file.Name))
                {
                    SourceStream.CopyToAsync(DestinationStream);
                }
            }
        }

        // Copy subfolders
        var folders = StartDirectory.EnumerateDirectories();
        foreach (var folder in folders)
        {
            // Create subfolder target path by concatenating folder name to original target UNC
            string target = Path.Combine(TargetUNC, folder.Name);
            Directory.CreateDirectory(target);

            // Recurse into the subfolder
            SynchFolders(folder.FullName, target);
        }
    }

希望这有帮助

答案 1 :(得分:1)

How to: Copy Directories是来自MSDN的文章,展示了如何完全按照您的需要进行操作。

答案 2 :(得分:0)

阅读本MSDN教程(正是您所需要的):http://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx

注意:如果您想使用SourceStream.CopyToAsync代替file.CopyTo,只需将其替换为原始代码段