原文网址:https://blog.csdn.net/shuikanshui/article/details/122809945
一、使用App.Config作为配置文件
1、项目增加应用程序配置文件App.config
2、文件设置为“如果较新则复制”
3、示例文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DBConString" value="数据库连接字符串"/>
</appSettings>
</configuration>
4、读取通用方法
public static string GetSettings(string key)
{
return System.Configuration.ConfigurationManager.AppSettings[key];
}
二、使用appsettings.json作为配置文件
1、在项目中添加appsettings.json文件,设置“复制到输出目录”为“如果较新则复制”
2、读取通用方法
static string GetSettings(string key)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
return configuration[key];
}
3、示例节点
{
"RabbitMQ": {
"host": "主机地址",
"user": "用户",
"password": "密码"
}
}
4、读取示例代码
var factory = new ConnectionFactory()
{ HostName = GetSettings("RabbitMQ:host"),
UserName = GetSettings("RabbitMQ:user"),
Password = GetSettings("RabbitMQ:password")
};
————————————————
版权声明:本文为CSDN博主「青云ing」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/shuikanshui/article/details/122809945
原文网址:http://t.zoukankan.com/chuankang-p-8780156.html
----------------------------------------
【Core】.NET Core中读取App.config配置文件
1.项目中添加App.config文件
因为.NET Core的项目本质是控制台应用,所以ConfigurationManager的API会去默认读取app.config配置文件,而不是web.config配置文件。
2.如果是asp.net迁移过来的配置文件,去除config中和需要的配置无关的内容,主要是<system.web>
、 <system.webServer>
、<system.codedom>
等典型asp.net标签。
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- To customize the asp.net core module uncomment and edit the following section. For more info see https://go.microsoft.com/fwlink/?linkid=838655 --> <!-- <system.webServer> <handlers> <remove name="aspNetCore"/> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/> </handlers> <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".logsstdout" /> </system.webServer> --> <appSettings> <add key="Email" value="[email protected]" /> </appSettings> <connectionStrings> <add name="TestCon" connectionString="Data Source=.;Initial Catalog=OWNDB;user id=sa;pwd=123456" /> </connectionStrings> </configuration>
3.引入【 System.Configuration.ConfigurationManager 】NUGET包
4.读取
var email = System.Configuration.ConfigurationManager.AppSettings["Email"];标签:读取,配置文件,ConfigurationManager,RabbitMQ,GetSettings,Net,config,控制台 From: https://www.cnblogs.com/bruce1992/p/17052721.html
var conn = System.Configuration.ConfigurationManager.ConnectionStrings["TestCon"];