【问题标题】:string value obtained from reading from json file , displays weirdly when using Path.Combine从 json 文件中读取的字符串值,使用 Path.Combine 时显示奇怪
【发布时间】:2020-06-03 15:25:27
【问题描述】:

我有一个功能,我可以扫描某个文件的给定路径并根据该文件中的信息处理一些信息。 json 语法中的这个文件 info.json 有一个名称和一个到某个目录的相对路径。 我想要做的只是从json文件中获取相对路径并打印出一个绝对路径

info.json文件中指定的相关文件如下,

{
  "Name": "testName",
  "OriginalPath": "new/File"
}

我要打印的绝对路径类似于:- D:\testDel\new\File 但实际值​​始终类似于 D:\testDel\new/File ,而我必须说这条路径仍然有效路径(当我执行 win 键 + RI 时可以导航到该目录),但就其显示方式而言,它看起来很乱。

关于我为什么会遇到这个问题的任何想法,我做错了什么,

我的代码如下

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);
                Console.WriteLine(fullPath);

            }
    public class DataModel
    {
        public string Name { get; set; }
        public string OriginalPath { get; set; }
    }

【问题讨论】:

  • fullPath = Path.Combine(folderpath, absolutePath).Replace("/", "\")
  • 这是一个非常弱的解决方案,因为 1)它是一种解决方法,而不是真正的解决方案 2)我收到一个错误 Error CS1010 Newline in constant @stuartd

标签: c# .net json path


【解决方案1】:

您可以使用Replace 方法和内置Path.AltDirectorySeparatorCharPath.DirectorySeparatorChar 字段更新来自JSON 的路径

string absolutePath = data.OriginalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string folderpath = Path.GetDirectoryName(file);

你是对的,路径D:\testDel\new/File是有效的,因为Windows同时支持正斜杠和反斜杠

【讨论】:

    【解决方案2】:

    将 Path.Combine(folderpath, absolutePath) 语句包装在 Path.GetFullPath() 中

    fullPath=Path.GetFullPath(Path.Combine(folderpath, absolutePath));
    

    这也将解析像../NewFilD:\NewFile这样的相关路径

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多