码迷,mamicode.com
首页 > 其他好文 > 详细

config文件的两种读取方式

时间:2016-07-08 17:49:40      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

1.项目默认的读取webconfig中的,代码如下

 1   public void GetAccounts()
 2 
 3         {      
 4 
 5             Configuration config=System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 6 
 7             //判断App.config配置文件中是否有Key(非null)
 8 
 9             if (ConfigurationManager.AppSettings.HasKeys())
10 
11              { 
12 
13                 //循环遍历出配置文件中的所有的键Key
14 
15                 foreach (string s in ConfigurationManager.AppSettings)
16 
17                 {
18 
19                     string[] nameAndPassword = s.Split(,);
20 
21                     Entity.Account account = new Entity.Account()
22 
23                     {
24 
25                         Name= nameAndPassword[0],
26 
27                         Username = nameAndPassword[1],
28 
29                         Password = nameAndPassword[2],
30 
31                         EmailAddress=nameAndPassword[3],
32 
33                     };
34 
35                     accounts.Add(account);
36 
37                 }
38 
39              }
40 
41            }
42 
43         }  

 


 

2.指定位置的读取方式(自己添加的config文件)

 

 1  public void GetAccounts(string path)
 2         {
 3             //FileInfo accountFile = new FileInfo(path);
 4             ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
 5             ecf.ExeConfigFilename = path;
 6             Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
 7 
 8             foreach (string s in config.AppSettings.Settings.AllKeys)
 9             {
10                 string[] nameAndPassword = s.Split(,);
11                 Entity.Account account = new Entity.Account()
12                 {
13                     Name = nameAndPassword[0],
14                     Username = nameAndPassword[1],
15                     Password = nameAndPassword[2],
16                     EmailAddress = nameAndPassword[3],
17                     IsAdmin = nameAndPassword[4]
18                 };
19 
20                 if (bool.Parse(account.IsAdmin))
21                 {
22                     AccountAdmin = account;
23                 }
24 
25                 accounts.Add(account);
26             }
27         }

其中path可以使用相对路径:

 string path = @"../Debug/Accounts.Config";

也可以使用绝对路径,根据项目需要添加,另外多说一句,如果想使用计划任务执行程序,必须使用绝对路径

 

config文件的两种读取方式

标签:

原文地址:http://www.cnblogs.com/michealm/p/5653893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!