首页 > 解决方案 > 使用 Path.Combine() 时源和目标必须不同

问题描述

我正在尝试为我的 RPG 创建一个批处理字符表创建器。当程序加载时,它会在其文件位置WORKINGDIR + WAITDIR查找任何具有标记的图片文件ReadyMaleFemale标记并将它们放入WORKINGDIR + LIVEDIRWORKINGDIR看起来像这样:

Debug // WORKINGDIR
├───Live // LIVEDIR
├───Wait // WAITDIR
├───Crew.exe // program
└───Other VS files

当代码运行System.IO.IOException: 'Source and destination path must be different.'时,当我尝试将文件从一个移动到另一个时会引发错误。不知何故sourcedestination变得等价。

const string LIVEDIR = "\\Live";
const string WAITDIR = "\\Wait";
List<string> files = new List<string>(Directory.EnumerateFiles(WORKINGDIR + WAITDIR, "*.jpeg", SearchOption.TopDirectoryOnly));
files.AddRange(Directory.EnumerateFiles(WORKINGDIR + WAITDIR, "*.png", SearchOption.TopDirectoryOnly));
files.AddRange(Directory.EnumerateFiles(WORKINGDIR + WAITDIR, "*.jpg", SearchOption.TopDirectoryOnly));
// ^ adds files that need to be looked through
string[] tags;
ShellFile shellFile;
foreach(string file in files)
{
    string source = Path.Combine(WORKINGDIR, WAITDIR, file);
    string destination = Path.Combine(WORKINGDIR, LIVEDIR, file);
    /*if (source == destination)
        throw new Exception();
    */ // This is also thrown
    shellFile = ShellFile.FromFilePath(Path.Combine(WORKINGDIR, WAITDIR, file));
    tags = shellFile.Properties.System.Photo.TagViewAggregate.Value;
    int i = 0;
    crewMember.Gender foo = crewMember.Gender.Female;
    if (tags == null)
        continue;
    foreach(string tag in tags)
    {
        if(tag == "Ready")
        {
            i++;
        }
        if(tag == "Female")
        {
            i++;
            foo = crewMember.Gender.Female;
        }
        else if(tag == "Male")
        {
            i++;
            foo = crewMember.Gender.Male;
        }
    }

    if(i>=2) // if it has two correct tags
    {
        Console.WriteLine(
            $"source:      {source}\n" +
            $"Destination: {destination}");
        // ^ also writes the same paths to console.
        Directory.Move(source, destination);
        // ^ Error
        crewMembers.Add(new crewMember(file, foo));
    }
}

我认为正在发生的事情是,无论出于何种原因Path.Combine(),都会返回先前生成的字符串而不是新字符串。有没有办法解决这个问题,还是我用错了?

标签: c#

解决方案


该方法Directory.EnumerateFiles给出了绝对路径,因此您的每个file变量都包含一个绝对路径。

如果您提供多个绝对路径Path.Combine,它将输出最后一个:

Path.Combine("C:\\", "workdir", "C:\\outdir\\test.txt")

产量

C:\outdir\test.txt

试试看)。

这是因为该Path.Combine方法试图根输出路径

但是,如果第一个参数以外的参数包含根路径,则任何先前的路径组件都将被忽略,并且返回的字符串以该根路径组件开头。

特别是对于将文件名作为用户输入的应用程序,这是一个常见的安全隐患

相反,要么首先使用Path.GetFileName获取纯文件名,要么,如果您有权访问 .NET Core,则使用新的更安全的Path.Join方法组合路径。


推荐阅读