使用Path.Combine后路径混有正反斜杠的问题咨询
问题分析与解决方案
为什么会出现混合斜杠的情况?
这个问题我之前也碰到过,其实原因很明确:你从info.json里读取的OriginalPath用的是正斜杠(/)作为分隔符,而Path.Combine方法在拼接路径时,不会自动将传入的路径片段里的分隔符转换成当前系统的默认分隔符(Windows系统默认是反斜杠\)。它只负责处理路径拼接的逻辑,会保留原片段里的分隔符,所以最终就出现了D:\testDel\new/File这种混合格式的路径。
怎么修复成统一的Windows路径格式?
最稳妥的方式是在拼接完路径后,用Path.GetFullPath()方法处理一下——它会自动把所有分隔符转换成当前系统的默认格式,同时还能处理路径里的相对路径、冗余分隔符等问题,让路径更规范。
修改后的代码如下:
string path = @"D:\testDel"; IEnumerable<string> foundFiles = Directory.EnumerateFiles(path, "info.json", SearchOption.AllDirectories); foreach (string file in foundFiles) { DataModel data = JsonConvert.DeserializeObject<DataModel>(File.ReadAllText(file)); string Name = data.Name; string absolutePath = data.OriginalPath; string folderpath = Path.GetDirectoryName(file); string fullPath = Path.Combine(folderpath, absolutePath); // 新增这一行,统一路径分隔符并规范化路径 string standardizedPath = Path.GetFullPath(fullPath); Console.WriteLine(standardizedPath); } public class DataModel { public string Name { get; set; } public string OriginalPath { get; set; } }
额外说明
如果你只是单纯想替换分隔符,也可以用fullPath.Replace('/', Path.DirectorySeparatorChar),但Path.GetFullPath()是更推荐的方式——它不仅能处理分隔符,还能帮你自动处理./、../这类相对路径标记,让路径逻辑更严谨。
内容的提问来源于stack exchange,提问作者Devss




