【问题标题】:The target path "" is a directory and not a file [closed]目标路径“”是目录而不是文件[关闭]
【发布时间】:2021-08-27 15:59:30
【问题描述】:

我正在尝试将文件复制到另一个文件夹,这是我的代码。

private static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
{
    foreach (var sourceFilePath in Directory.GetFiles(source.FullName))
    {
        FileInfo file;

        if(IsAccesable(sourceFilePath, out file))
        {
            file.CopyTo(target.FullName); //ERROR HERE
        }
        else
        {
            //DO WORKAROUND
        }
    }

    foreach(var sourceSubDirectoryPath in Directory.GetDirectories(source.FullName))
    {
        DirectoryInfo directory;

        if(IsAccesable(sourceSubDirectoryPath, out directory))
        {
            var targetSubDictionary = target.CreateSubdirectory(Path.Combine(target.FullName, sourceSubDirectoryPath));
            CopyDirectory(directory, targetSubDictionary);
        }
        else
        {
            //DO WORKAROUND
        }
    }
}

我不断收到错误消息:目标路径“”是目录而不是文件

完整的源路径:

"c:\\Hypixel Bots Interface\\.gitattributes"

完整的目标路径:

"C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface"

【问题讨论】:

  • 当你复制一个文件时,你必须告诉它要复制到哪个文件,但你给它的是一个目录

标签: c# directory


【解决方案1】:

您的路径中没有文件。例如,在您的文件夹中创建一个文件并将其命名为 test.txt,然后再次运行您的代码以验证错误是否会消失。

“C:\Users\wout\source\repos\FileCloner\FileCloner\bin\Debug\net5.0\Target\Hypixel Bots Interface\.gitattributes\test.txt”

【讨论】:

    【解决方案2】:

    正如错误所说,您希望 targetPath 是一个文件名。您只是指向一个文件夹。

    "C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface\\.gitattributes"
    

    这将指向该目录中的一个新文件

    【讨论】:

    • 我想把它放在一个文件夹里,在文件夹里新建一个文件。
    • 是的。因此,在文件路径的末尾,您需要像我上面那样添加文件名。它将看到不存在具有该名称的文件,因此它将创建一个新文件。
    • 帮助,它说路径 C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\ \Hypixel Bots 界面确实已经存在。
    • 如果你想再次运行它,你需要告诉它覆盖文件。 file.CopyTo(target.FullName, true) docs.microsoft.com/en-us/dotnet/api/… 以后提问前请参考官方文档。
    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2013-09-04
    • 2012-08-18
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多