当前位置:网站首页>C#【必备技能篇】ConfigurationManager 类的使用(文件App.config的使用)
C#【必备技能篇】ConfigurationManager 类的使用(文件App.config的使用)
2022-07-05 08:43:00 【明如正午】
前言
在项目中,我们习惯使用 ConfigurationManager 来读取一些常量。如链接数据库字符串、一些需配置的数据(微信、QQ、支付宝)等的配置。我们需要把这些数据记录在 app.config 或者 web.config 中。接下来我们具体看一下 ConfigurationManager :
一、介绍
命名空间:System.Configuration
程序集: System.Configuration.dll
引用:在使用中,如果出现“当前上下文中不存在名称:ConfigurationManager”,你就要检查有没有引用程序集和命名空间了。
ConfigurationManager类:
包含属性(AppSettings、ConnectionStrings )、
方法(GetSection、OpenExeConfiguration、OpenExeConfiguration、OpenMachineConfiguration、OpenMappedExeConfiguration、OpenMappedExeConfiguration、OpenMappedMachineConfiguration、RefreshSection)
二、使用
2.1 通过 AppSettings 来获取数据
简单使用案例:
using System;
using System.Configuration;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ReadAllSettings();
ReadSetting("Setting1");
ReadSetting("NotValid");
AddUpdateAppSettings("NewSetting", "May 7, 2014");
AddUpdateAppSettings("Setting1", "May 8, 2014");
ReadAllSettings();
Console.ReadLine();
}
static void ReadAllSettings()
{
try
{
var appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0)
{
Console.WriteLine("AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
}
}
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
static void ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not Found";
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
}
}
在文件 App.config 中配置:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<appSettings>
<add key="Setting1" value="May 5,2018"/>
<add key="Setting2" value="May 5,2017"/>
</appSettings>
</configuration>
运行结果:
2.2 通过使用 ConnectionStrings 来获取数据
实例如下:
using System;
using System.Configuration;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ReadUsers();
}
static void ReadUsers()
{
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
string queryString = "SELECT Id, Name FROM abpusers;";
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(queryString, connection);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
}
}
}
}
}
在 App.config 中配置数据库链接字符串:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="Setting1" value="May 5,2018"/>
<add key="Setting2" value="May 5,2017"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="Server=127.0.0.1; Database=CityManage; Trusted_Connection=False; Uid=root; pwd=zxx123456;" providerName="System.Data.SqlClient" />
<add name="Abp.Redis.Cache" connectionString="localhost" />
</connectionStrings>
</configuration>
边栏推荐
- 319. Bulb switch
- Redis implements a high-performance full-text search engine -- redisearch
- Search data in geo database
- 猜谜语啦(6)
- ABC#237 C
- asp.net(c#)的货币格式化
- Arduino+a4988 control stepper motor
- Warning: retrying occurs during PIP installation
- [three tier architecture]
- Low code platform | apaas platform construction analysis
猜你喜欢
随机推荐
[three tier architecture]
某公司文件服务器迁移方案
Lori remote control commissioning record
Xrosstools tool installation for X-Series
Lori remote control LEGO motor
Task failed task_ 1641530057069_ 0002_ m_ 000000
每日一题——输入一个日期,输出它是该年的第几天
L298N module use
Business modeling of software model | overview
Business modeling | process of software model
猜谜语啦(10)
猜谜语啦(6)
Guess riddles (10)
287. Looking for repeats - fast and slow pointer
猜谜语啦(4)
MATLAB小技巧(28)模糊综合评价
【日常训练】1200. 最小绝对差
Low code platform | apaas platform construction analysis
Infix expression evaluation
【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III