.NET: 配置文件

时间:2021-07-03 20:27:45

VS里项目->添加新项->应用程序配置文件

 <?xml version="1.0" encoding="utf-8" ?>
 <configuration>
   <appSettings>
     <add key="userName" value="Gaby"/>
     <add key="/>
   </appSettings>
   <connectionStrings>
     <add name="constr" connectionString="server=localhost;database=persons;uid=root;pwd=0000"/>
   </connectionStrings>
 </configuration>

在主程序里可以访问

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Xml;
 using System.Xml.Linq;
 using System.Configuration;

 namespace ConsoleTest
 {
     public class Program
     {
         static void Main(string[] args)
         {
             string userName = ConfigurationManager.AppSettings["userName"];
             string pwd = ConfigurationManager.AppSettings["password"];
             Console.WriteLine(userName);
             Console.WriteLine(pwd.ToString());
             string connectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString.ToString();
             Console.WriteLine(connectionString);
         }
     }
 }

如果出现已过时的警告,则要添加System.Configuration引用