当前位置:网站首页>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>
边栏推荐
- C语言标准函数scanf不安全的原因
- Halcon snap, get the area and position of coins
- [three tier architecture]
- 猜谜语啦(3)
- [牛客网刷题 Day4] JZ35 复杂链表的复制
- Example 001: the number combination has four numbers: 1, 2, 3, 4. How many three digits can be formed that are different from each other and have no duplicate numbers? How many are each?
- Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
- Mathematical modeling: factor analysis
- Run菜单解析
- 【三层架构】
猜你喜欢

It cold knowledge (updating ing~)
![[nas1] (2021cvpr) attentivenas: improving neural architecture search via attentive sampling (unfinished)](/img/3b/c94b8466370f4461875c85b4f66860.png)
[nas1] (2021cvpr) attentivenas: improving neural architecture search via attentive sampling (unfinished)
Example 001: the number combination has four numbers: 1, 2, 3, 4. How many three digits can be formed that are different from each other and have no duplicate numbers? How many are each?

Halcon affine transformations to regions

Example 002: the bonus paid by the "individual income tax calculation" enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increase

TypeScript手把手教程,简单易懂

【NOI模拟赛】汁树(树形DP)
![[牛客网刷题 Day4] JZ55 二叉树的深度](/img/f7/ca8ad43b8d9bf13df949b2f00f6d6c.png)
[牛客网刷题 Day4] JZ55 二叉树的深度

我从技术到产品经理的几点体会

Example 003: a complete square is an integer. It is a complete square after adding 100, and it is a complete square after adding 168. What is the number?
随机推荐
Sword finger offer 06 Print linked list from end to end
It cold knowledge (updating ing~)
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
Classification of plastic surgery: short in long long long
Sword finger offer 09 Implementing queues with two stacks
Guess riddles (142)
Bluebridge cup internet of things competition basic graphic tutorial - clock selection
【日常训练--腾讯精选50】557. 反转字符串中的单词 III
Basic number theory - fast power
Halcon Chinese character recognition
多元线性回归(sklearn法)
Low code platform | apaas platform construction analysis
RT-Thread内核快速入门,内核实现与应用开发学习随笔记
[matlab] matlab reads and writes Excel
2022.7.4-----leetcode.1200
猜谜语啦(7)
Example 002: the bonus paid by the "individual income tax calculation" enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increase
Adaboost使用
C语言标准函数scanf不安全的原因
Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.