我正在嘗試將檔案夾路徑保存在 json 檔案中,但我似乎無法找到/弄清楚如何讓它正確決議它
我正在使用以下代碼撰寫 json 檔案
string location = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string userDataPreset = @"{UserData: [{Language: ""NL"", location: " location "}]}";
File.WriteAllText(userData, userDataPreset);
這將創建以下 json:
{
"UserData": [
{
"Language": "NL",
"location": C:\Users\stage\OneDrive\Documenten
}
]
}
但我需要它變成下面這樣,帶有雙 // 和“”:
{
"UserData": [
{
"Language": "NL",
"location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}
我缺少什么來正確決議這條路徑?
uj5u.com熱心網友回復:
要修復字串,您可以使用 Escape 方法
location=Regex.Escape(location);
但最可靠的方法是創建一個匿名物件并序列化它
var data = new { UserData = new[] { new { Language = "NL", Location = location } } };
var json = System.Text.Json.JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true});
File.WriteAllText(userData, json);
json
{
"UserData": [
{
"Language": "NL",
"Location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504933.html
