步驟
- 讀取配置文件轉換成字符串,代碼如下
string contents = System.IO.File.ReadAllText("config.json");
注意:該語句會拋出文件不存在異常。
- 使用
Newtonsoft.Json
將json字符串轉換成類的對象,完整代碼如下所示
public class Init
{
public static InitInfo init = new InitInfo();
public Init(){
try
{
string contents = System.IO.File.ReadAllText("config.json");
//Shell.WriteLine("ini 配置文件\r\n" + JsonConvert.SerializeObject(init));
init = JsonConvert.DeserializeObject<InitInfo>(contents);
Shell.WriteLine("初始化配置文件內容\r\n\r\n" + contents + "\r\n\r\n");
}
catch (Exception)
{
throw;
}
}
}
注意事項
-
Newtonsoft.Json
需要添加引用,下載地址如下所示
https://www.newtonsoft.com/json -
可以使用
JsonConvert.SerializeObject(init)
語句生成配置信息,打印在控制台,C-V。