CopyTo() 到尚不存在的目录

发布于 2024-07-23 03:14:01 字数 1156 浏览 1 评论 0原文

我想将文件 c:\a1\b2\c3\foo.txt 复制到 d:\a1\b2\c3\foo.txt。 D 驱动器上不存在子目录,如果我尝试直接执行 CopyTo(),我将收到 IO 异常。 我无法找到任何内置的 c# 函数来完成创建丢失目录的脏工作。 所以我写道:

FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");

if (!destDir.Exists) // false
    CreateDirectory(destDir, null);
file.CopyTo(file.FullName.Replace("c:", "d:"), true);

private void CreateDirectory(DirectoryInfo endDir, Stack<DirectoryInfo> trail)
{
    if (trail == null)
    {
        trail = new Stack<DirectoryInfo>();
        trail.Push(endDir);
    }

    // remove last directory - c:\a1\b2\c3, c:\a1\b2, c:\a1
    Match theMatch = Regex.Match(endDir.FullName, @".*(?=\\\w*\Z)"); 
    DirectoryInfo checkDir = new DirectoryInfo(theMatch.ToString());
    if (!checkDir.Exists)
    {
        trail.Push(checkDir);
        CreateDirectory(checkDir, trail);
    }
    else
        foreach (DirectoryInfo dir in trail)
            Directory.CreateDirectory(dir.FullName);
}

这非常复杂,正如他们喜欢在深夜的电视广告上说的那样,“一定有更好的方法!”

问题:如何让上面的函数高效运行? 我是否缺少一个内置方法,该方法已经完成了我正在做的所有事情?

I want to copy the file c:\a1\b2\c3\foo.txt to d:\a1\b2\c3\foo.txt. The subdirectories don't exist on the D drive, and if I try to do a direct CopyTo() I'll get an IO exception.
I haven't been able to find any built-in c# function that does the dirty work of creating the missing directories. So I wrote this:

FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");

if (!destDir.Exists) // false
    CreateDirectory(destDir, null);
file.CopyTo(file.FullName.Replace("c:", "d:"), true);

private void CreateDirectory(DirectoryInfo endDir, Stack<DirectoryInfo> trail)
{
    if (trail == null)
    {
        trail = new Stack<DirectoryInfo>();
        trail.Push(endDir);
    }

    // remove last directory - c:\a1\b2\c3, c:\a1\b2, c:\a1
    Match theMatch = Regex.Match(endDir.FullName, @".*(?=\\\w*\Z)"); 
    DirectoryInfo checkDir = new DirectoryInfo(theMatch.ToString());
    if (!checkDir.Exists)
    {
        trail.Push(checkDir);
        CreateDirectory(checkDir, trail);
    }
    else
        foreach (DirectoryInfo dir in trail)
            Directory.CreateDirectory(dir.FullName);
}

That's pretty involved, and as they like to say on late-night informercials, "There's got to be a better way!"

Question: how would I make the function above move efficient? And am I missing a built-in method that already does everything I'm doing the hard way?

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

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

发布评论

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

评论(4

享受孤独 2024-07-30 03:14:01
Directory.CreateDirectory(@"c:\foo\bar\baz");

记录为创建所有必需的目录,并且适用于我。

指定的任何和所有目录
路径已创建,除非它们已经创建
存在或者除非路径的某些部分是
无效的。 路径参数指定
目录路径,而不是文件路径。 如果
该目录已经存在,这个
方法什么也不做。

Directory.CreateDirectory(@"c:\foo\bar\baz");

Documented as creating all required directories, and works for me.

Any and all directories specified in
path are created, unless they already
exist or unless some part of path is
invalid. The path parameter specifies
a directory path, not a file path. If
the directory already exists, this
method does nothing.

浸婚纱 2024-07-30 03:14:01

或者您可以直接使用Directory.CreateDirectory(),因为它已经创建了所有中间路径。

Or you can just use Directory.CreateDirectory() directly, since it already creates all the intermediate paths.

猫瑾少女 2024-07-30 03:14:01

奇怪的是,我正在使用 CopyTo ,它会在目标位置自动创建所有子目录。

我的代码非常简单:

// file is FileInfo and target is DirectoryInfo
file.CopyTo(target);

Strange, I am working with CopyTo and it creates all the subdirectories automatically in the destination location.

My code is as simple as can be:

// file is FileInfo and target is DirectoryInfo
file.CopyTo(target);
凉墨 2024-07-30 03:14:01

DirectoryInfo 实例可以 通过 destDir.Create() 创建自己的路径,并进行所有您想要的检查:

FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");

destDir.Create(); // <-- makes it if it doesn't exist, otherwise noop

var newPath = 
   Path.Combine(destDir.FullName, Path.GetFileName(file)); // <-- just to be safe...
file.CopyTo(newPath, true);

在这里找到这个:https://stackoverflow.com/a/2955425/1037948

A DirectoryInfo instance can create its own path with all the checking you want via destDir.Create():

FileInfo file = new FileInfo(@"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");

destDir.Create(); // <-- makes it if it doesn't exist, otherwise noop

var newPath = 
   Path.Combine(destDir.FullName, Path.GetFileName(file)); // <-- just to be safe...
file.CopyTo(newPath, true);

Found this out here: https://stackoverflow.com/a/2955425/1037948

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