• C# ConfigurationManager 类的使用


    C# ConfigurationManager 类的使用

    一、前言

      在项目中,我们习惯使用 ConfigurationManager 来读取一些常量。如链接数据库字符串、一些需配置的数据(微信、QQ、支付宝)等的配置。我们需要把这些数据记录在 app.config 或者 web.config 中。接下来我们具体看一下 ConfigurationManager  :

    二、介绍

       命名空间:System.Configuration

       程序集: System.Configuration.dll

      引用:在使用中,如果出现“ 当前上下文中不存在名称:ConfigurationManager ”,你就要检查有没有引用程序集和命名空间了。

      ConfigurationManager类: 包含属性(AppSettings、ConnectionStrings )、方法(GetSection、OpenExeConfiguration、OpenExeConfiguration、OpenMachineConfiguration、OpenMappedExeConfiguration、OpenMappedExeConfiguration、OpenMappedMachineConfiguration、RefreshSection)

    三、使用

      通过 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();  
            }  
    
            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.1" />
      </startup>
      <appSettings>
        <add key="Setting1" value="May 5,2018"/>
        <add key="Setting2" value="May 5,2017"/>
      </appSettings>
    </configuration>

    复制代码

    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++之分文件编写
    C++之冒泡排序实现
    cobaitstrike之修改特征
    cobaitstrike之DNS上线
    网盘搜索【不断更新ing】
    CVE-2021-2109 Weblogic Server远程代码执行
    C++之一维&二维数组
    CDH-5.12.2安装教程
    linux安装mysql教程
  • 原文地址:https://www.cnblogs.com/grj001/p/12224522.html
Copyright © 2020-2023  润新知