我注意到我的代码将文件写入了错误的文件夹,因此我添加了一些日志记录,结果令我吃惊。我的代码:
string savePath = Path.Combine(mapping.Folder, fileMeta.RelativePath, fileMeta.Filename);
logger.Info(mapping.Folder);
logger.Info(fileMeta.RelativePath);
logger.Info(fileMeta.Filename);
logger.Info("savepath: {0}", savePath);
这是写入日志的内容:
C:\Sync
\0100_MACHINES
Layout US.pdf
savepath: \0100_MACHINES\Layout US.pdf
谁能给出可能的原因,为什么 Path.Combine
省略第一个参数,而只组合第二个和第三个?有趣的是,这只发生在一台机器上。
最佳答案
第二个参数以反斜杠字符开头。这导致 Path.Combine
省略了之前的部分。通过添加 TrimStart
解决了这个问题:
string savePath = Path.Combine(mapping.Folder,
fileMeta.RelativePath.TrimStart('\\'),
fileMeta.Filename.TrimStart('\\'));
关于c# - Path.Combine 省略其中一个参数的可能原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136564/