如何在 .NET 中复制文件夹以及所有子文件夹和文件? [英] How do I copy a folder and all subfolders and files in .NET?

查看:43
本文介绍了如何在 .NET 中复制文件夹以及所有子文件夹和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
复制整个的最佳方式C#中目录的内容

我想将文件夹及其所有子文件夹和文件从一个位置复制到 .NET 中的另一个位置.这样做的最佳方法是什么?

I'd like to copy folder with all its subfolders and file from one location to another in .NET. What's the best way to do this?

我在 System.IO.File 类上看到了 Copy 方法,但想知道是否有比爬行目录树更简单、更好或更快的方法.

I see the Copy method on the System.IO.File class, but was wondering whether there was an easier, better, or faster way than to crawl the directory tree.

推荐答案

嗯,Steve 引用了 VisualBasic.dll 实现,这里有一些我用过的东西.

Well, there's the VisualBasic.dll implementation that Steve references, and here's something that I've used.

private static void CopyDirectory(string sourcePath, string destPath)
{
    if (!Directory.Exists(destPath))
    {
        Directory.CreateDirectory(destPath);
    }

    foreach (string file in Directory.GetFiles(sourcePath))
    {
        string dest = Path.Combine(destPath, Path.GetFileName(file));
        File.Copy(file, dest);
    }

    foreach (string folder in Directory.GetDirectories(sourcePath))
    {
        string dest = Path.Combine(destPath, Path.GetFileName(folder));
        CopyDirectory(folder, dest);
    }
}

这篇关于如何在 .NET 中复制文件夹以及所有子文件夹和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆