c# - 使用 Path.Combine() 时源和目标必须不同
问题描述
我正在尝试为我的 RPG 创建一个批处理字符表创建器。当程序加载时,它会在其文件位置WORKINGDIR + WAITDIR
查找任何具有标记的图片文件Ready
,Male
并Female
标记并将它们放入WORKINGDIR + LIVEDIR
。WORKINGDIR
看起来像这样:
Debug // WORKINGDIR
├───Live // LIVEDIR
├───Wait // WAITDIR
├───Crew.exe // program
└───Other VS files
当代码运行System.IO.IOException: 'Source and destination path must be different.'
时,当我尝试将文件从一个移动到另一个时会引发错误。不知何故source
,destination
变得等价。
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()
,都会返回先前生成的字符串而不是新字符串。有没有办法解决这个问题,还是我用错了?
解决方案
该方法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
方法组合路径。
推荐阅读
- azure-devops - 使用 Azure Dacpac 任务时释放管道错误
- asp.net-core-mvc - 如何使用 Swashbuckle.AspNetCore.Swagger 在 asp.net 核心中忽略/更改模型参数
- android - React Native [Android] 中的 FIrebase 云消息传递
- html - Django 视图打开不同的内容
- android - 如何使用 Flutter 制作“全选”和“取消全选”按钮?
- javascript - 如何调用 API 以使其返回您请求的任何内容以及如何减少 Vuejs 中的观察者数量
- sql - postgres:查询百分比执行
- spring - 将 Angular 10 与 Spring 安全连接以使用自定义登录页面时出现问题
- python - Python 错误:NameError:名称未定义
- r - 如何使用防火墙阻止 R 访问互联网?