使用Path.Combine()时,源和目标必须不同

Dos*_*cio 4 c#

我正在尝试为我的RPG创建一个批处理charsheet创建器。当程序加载,它看起来在其文件位置WORKINGDIR + WAITDIR对于有代码的所有图片文件ReadyMaleFemale标签,并将它们放入WORKINGDIR + LIVEDIRWORKINGDIR看起来像这样:

Debug // WORKINGDIR
????Live // LIVEDIR
????Wait // WAITDIR
????Crew.exe // program
????Other VS files
Run Code Online (Sandbox Code Playgroud)

运行代码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));
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为这是由于某种原因Path.Combine()而返回的是先前生成的字符串,而不是新的字符串。有没有解决的办法,或者我用错了吗?

Jan*_*ann 6

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

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

Path.Combine("C:\\", "workdir", "C:\\outdir\\test.txt")
Run Code Online (Sandbox Code Playgroud)

产量

C:\outdir\test.txt
Run Code Online (Sandbox Code Playgroud)

尝试)。

这是因为该Path.Combine方法尝试将输出路径设为

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

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

而是要么Path.GetFileName先获取原始文件名,要么如果可以访问.NET Core,则使用新的更安全的Path.Join方法合并路径。