当前位置:网站首页>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


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 .
   Insert picture description here

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 :
Key: Setting1 Value: May 5,2018 Key: Setting2 Value: May 5,2017 May 5,2018 Not Found Key: Setting1 Value: May 8, 2014 Key: Setting2 Value: May 5,2017 Key: NewSetting Value: May 7, 2014

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>
原网站

版权声明
本文为[As bright as noon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050843242610.html