• 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>

    简单小节,资源来源于:官网教程

  • 相关阅读:
    习惯
    mysql
    mysql
    mysql
    MYSQL
    MYSQL
    mysql
    手动从Spring中获取指定对象
    jdbc连接数据库
    java代码调用exe(cmd命令)
  • 原文地址:https://www.cnblogs.com/gzbit-zxx/p/10396548.html
Copyright © 2020-2023  润新知