如何复制 .NET 中的文件夹及其所有子文件夹和文件?

发布于 2024-07-26 01:01:26 字数 337 浏览 3 评论 0原文

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

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

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

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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深海夜未眠 2024-08-02 01:01:26

好吧,Steve 引用了 VisualBasic.dll 实现,这是我使用过的东西。

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);
    }
}

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);
    }
}
℉絮湮 2024-08-02 01:01:26

Michal Talaga 在他的 帖子 中引用了以下内容:

  • Microsoft 关于为什么不应该有 Directory.Copy( ) 在.NET 中运行。
  • Microsoft.VisualBasic.dll 程序集中的 CopyDirectory() 实现。

但是,基于 File.Copy()Directory.CreateDirectory() 的递归实现应该足以满足最基本的需求。

Michal Talaga references the following in his post:

  • Microsoft's explanation about why there shouldn't be a Directory.Copy() operation in .NET.
  • An implementation of CopyDirectory() from the Microsoft.VisualBasic.dll assembly.

However, a recursive implementation based on File.Copy() and Directory.CreateDirectory() should suffice for the most basic of needs.

不爱素颜 2024-08-02 01:01:26

如果你没有得到任何更好的东西......也许使用Process.Start来启动robocopy.exe

If you don't get anything better... perhaps use Process.Start to fire up robocopy.exe?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文