当前位置:网站首页>C [essential skills] use of configurationmanager class (use of file app.config)
C [essential skills] use of configurationmanager class (use of file app.config)
2022-07-05 08:47:00 【As bright as noon】
List of articles
Preface
In the project , We are used to using ConfigurationManager To read some constants . Such as linked database string 、 Some data to be configured ( WeChat 、QQ、 Alipay ) Etc . We need to record these data in app.config perhaps web.config in . Next, let's take a specific look at ConfigurationManager :
One 、 Introduce
Namespace :System.Configuration
Assembly : System.Configuration.dll
quote : In the use of , If appear “ The name... Does not exist in the current context :ConfigurationManager”, You need to check whether there are referenced assemblies and namespaces .
ConfigurationManager class :
Include properties (AppSettings、ConnectionStrings )、
Method (GetSection、OpenExeConfiguration、OpenExeConfiguration、OpenMachineConfiguration、OpenMappedExeConfiguration、OpenMappedExeConfiguration、OpenMappedMachineConfiguration、RefreshSection)
Two 、 Use
2.1 adopt AppSettings To get data
Simple use cases :
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");
}
}
}
}
In the file App.config Middle configuration :
<?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>
Running results :
2.2 By using ConnectionStrings To get data
Examples are as follows :
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]));
}
}
}
}
}
}
stay App.config Configure database link string in :
<?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
Pytorch entry record
Xrosstools tool installation for X-Series
Ros-10 roslaunch summary
[matlab] matlab reads and writes Excel
Programming implementation of ROS learning 2 publisher node
Arduino operation stm32
[牛客网刷题 Day4] JZ55 二叉树的深度
Agile project management of project management
Run menu analysis
随机推荐
Basic number theory -- Euler function
整形的分类:short in long longlong
[牛客网刷题 Day4] JZ32 从上往下打印二叉树
Agile project management of project management
Guess riddles (6)
How to manage the performance of R & D team?
Use and programming method of ros-8 parameters
[牛客网刷题 Day4] JZ55 二叉树的深度
深度学习模型与湿实验的结合,有望用于代谢通量分析
Search data in geo database
MPSoC QSPI Flash 升级办法
猜谜语啦(9)
Programming implementation of subscriber node of ROS learning 3 subscriber
Esphone retrofits old fans
Esphone Feixun DC1 soft change access homeassstant
猜谜语啦(5)
[牛客网刷题 Day4] JZ35 复杂链表的复制
TypeScript手把手教程,简单易懂
golang 基础 —— golang 向 mysql 插入的时间数据和本地时间不一致
L298N module use