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

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

问题描述


可能重复:

最佳方式复制C#中的目录的全部内容

Possible Duplicate:
Best way to copy the entire contents of a directory in C#

我想将其所有子文件夹和文件的文件夹从一个位置复制到另一个位置。这是最好的方法是什么?

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类的复制方法,但是想知道是否有一个更简单,更好或更快方法比抓取目录树。

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天全站免登陆