桌面应用程序,通常使用app.config;Web应用程序,则使用web.config。
using System.Configuration;
string dbConnectionString = ConfigurationManager.AppSettings["DatabaseConnectionString"];
string appTitle = ConfigurationManager.AppSettings["ApplicationTitle"];
JSON:是一种轻量级的数据交换格式,易于阅读和编写。在C#中,可以使用如Newtonsoft.Json等库将JSON配置文件读取为对象,适用于跨平台应用程序。appsettings.json示例:
{
"Database": {
"ConnectionString": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
},
"Application": {
"Title": "My Application"
}
}
C#读取配置文件appsettings.json(使用Newtonsoft.Json库):
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
string jsonFilePath = "appsettings.json";
string json = File.ReadAllText(jsonFilePath);
JObject jsonObject = JObject.Parse(json);
string dbConnectionString = (string)jsonObject["Database"]["ConnectionString"];
string appTitle = (string)jsonObject["Application"]["Title"];