1. 程式人生 > >C#更改相對路徑下json檔案的做法

C#更改相對路徑下json檔案的做法

使用string.Substring切割字串返回上一級目錄

1 string filePath = Directory.GetCurrentDirectory(); //假如路徑為C:\aa\bb\cc\dd\ee
2 
3 filePath = filePath.Substring(0, filePath.LastIndexOf("\\"));  //dd目錄
4 filePath = filePath.Substring(0, filePath.LastIndexOf("\\"));  //cc目錄
5 filePath = filePath.Substring(0, filePath.LastIndexOf("
\\")); //bb目錄 6 7 filePath = filePath + "\\ff\\gg\\a.txt"; //file=C:\aa\bb\ff\gg\a.txt 目標路徑

更新json檔案:

1 {
2      "name":"gg",
3      "age":15
4 }

讀檔案-->修改目標值-->寫入檔案:

1 string jsonStr = File.ReadAllText(filePath, Encoding.Default);
2 JObject jo = JObject.Parse(jsonStr);   //解析Json
3 jo["
age"] = 20; 4 string convertString = Convert.ToString(jo); 5 File.WriteAllText(filePath, convertString); //將轉換後的檔案寫入

轉換後的json檔案:

{
"name":"gg",
"age":20
}

Over