C#读取App.config/Web.config

读取需要添加 System.Configuration 引用,

两种方式添加:

1:.NETFramework程序可以在引用右击添加引用,然后添加System.Configuration 

2:引入Nuget 包:Install-Package   System.Configuration.ConfigurationManager 

 

实例如下:

 

"1.0" encoding="utf-8" ?>

  
    "v4.0" sku=".NETFramework,Version=v4.5" />
  
  
    "a" value="A"/>
    "b" value="B"/>
    "c" value="C"/>
  
  
    "MSSQL" connectionString="Server..." providerName="111"/>
    "MYSQL" connectionString="Server....." providerName="222"/>
  
App.config

 

using System;
using System.Configuration;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ConfigurationManager.AppSettings["a"]);
            Console.WriteLine(ConfigurationManager.AppSettings["b"]);
            Console.WriteLine(ConfigurationManager.AppSettings["c"]);
            Console.WriteLine();
            Console.WriteLine(ConfigurationManager.ConnectionStrings["MSSQL"].ConnectionString);
            Console.WriteLine(ConfigurationManager.ConnectionStrings["MSSQL"].ProviderName);
            Console.WriteLine();
            Console.WriteLine(ConfigurationManager.ConnectionStrings["MYSQL"].ConnectionString);
            Console.WriteLine(ConfigurationManager.ConnectionStrings["MYSQL"].ProviderName);
        }
    }
}
读取App.config

 

//Asp.Net应用程序(MVC)读取Web.config
string name = System.Web.Configuration.WebConfigurationManager.AppSettings["name"];
读取Web.config

你可能感兴趣的:(C#读取App.config/Web.config)