1. 程式人生 > >Asp.Net讀取配置文件

Asp.Net讀取配置文件

-- etime absolute exp static from ont settings 緩存

為了不使自己寫的代碼看著臃腫,有些固定的值抽取出來,放入配置文件裏,這樣,不失為一種好的編碼習慣。這裏介紹兩種不同的文件格式:

一、AppSetting.config(.config格式)

1、首先,配置一下

1 <?xml version="1.0" encoding="utf-8"?>
2 <appSettings>
3   <!--糾錯信息處理狀態-->
4   <add key="CorrectState" value="已處理:0;未處理:1" />
5   <!--調用接口 地址配制-->
6   <add key="Api_BaseUrl
" value="http://172.16.16.68:8321/"/> 7 </appSettings>

2、讀取唯一值

 1         /// <summary>
 2         /// 通過key,獲取appSetting的值
 3         /// </summary>
 4         /// <param name="key">key</param>
 5         /// <returns>value</returns>
 6         public static string GetWebConfigValueByKey(string
key) 7 { 8 string value = string.Empty; 9 Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); 10 AppSettingsSection appSetting = (AppSettingsSection)config.GetSection("
appSettings"); 11 if (appSetting.Settings[key] != null)//如果不存在此節點,則添加 12 { 13 value = appSetting.Settings[key].Value; 14 } 15 config = null; 16 return value; 17 }

3、讀取多個值

 1  /// <summary>
 2         /// 如果值為 "已審核:1;待審核:0"  形式 ,可通過該函數獲取該appsetting值的指定value對應的key
 3         /// </summary>
 4         /// <param name="appSettingName"></param>
 5         /// <returns></returns>
 6         public static string GetKVofKey(string appSettingName, string value)
 7         {
 8             List<KV> l = new List<KV>();
 9             string str = GetWebConfigValueByKey(appSettingName);
10             string[] arr = str.Split(;);
11             string rs = "";
12             if (arr.Length > 0)
13             {
14                 int length = arr.Length;
15                 for (int i = 0; i < length; i++)
16                 {
17                     if (arr[i].Split(:)[1] == value)
18                     {
19                         rs = arr[i].Split(:)[0];
20                     }
21                 }
22             }
23             return rs;
24         }

所用類

1 1     public class KV
2 2     {
3 3         public string k;
4 4         public string v;
5 5     }

二、Api.ini

1、配置文件

1 #微信支付
2 [WeiXinPay]
3 appId=wx1***1
4 partnerid=1***1
5 appSecret=6***5 
6 key=N**C

2、ApiHelper.cs(類)

 1 public class ApiHelper
 2     {
 3         /// <summary>
 4         /// 配置文件虛擬路徑
 5         /// </summary>
 6         private const string ConfigFile = "~/Config/Api.ini";
 7         /// <summary>
 8         /// 獲取配置節
 9         /// </summary>
10         /// <typeparam name="T">節點類型(引用類型)</typeparam>
11         /// <param name="section">節點名稱</param>
12         /// <returns></returns>
13         public static T GetConfigureSection<T>(string section)
14             where T:class
15         {
16             SharpConfig.Configuration configuration = GetIniConfiguration();
17             return configuration[section].CreateObject<T>();
18         }
19         public static string GetPath(string path)
20         {
21             if (HttpContext.Current !=null)
22             {
23                 return HttpContext.Current.Server.MapPath(path);
24             }
25             path = path.Replace("/","\\");
26             if (path.StartsWith("\\"))
27             {
28                 path = path.Substring(path.IndexOf(\\, 1)).TrimStart(\\);
29             }
30             return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,path);
31         }
32         /// <summary>
33         /// 
34         /// </summary>
35         /// <returns></returns>
36         public static SharpConfig.Configuration GetIniConfiguration() 
37         {
38             const string SYSTEM_API_CONFIG = "SYSTEM_API_CONFIG";//配置Key
39             //如果緩存存在,則提取緩存數據
40             if (RuntimeCacheHelper.IsExists(SYSTEM_API_CONFIG))
41             {
42                 return RuntimeCacheHelper.Get<SharpConfig.Configuration>(SYSTEM_API_CONFIG);
43             }
44                 //從配置文件中加載,並緩存配置
45             else
46             {
47                 SharpConfig.Configuration configuration = null;
48                 String strConfigAbsolutePath = GetPath(ConfigFile);
49                 configuration = SharpConfig.Configuration.LoadFromFile(strConfigAbsolutePath);
50                 //緩存對象
51                 RuntimeCacheHelper.Save(SYSTEM_API_CONFIG,configuration,strConfigAbsolutePath,new TimeSpan(365,0,0,0,0));
52                 return configuration;
53             }
54         }
55     }

緩存類

 1 public class RuntimeCacheHelper
 2     {
 3         public static bool IsExists(string Name)
 4         {
 5             return (HttpRuntime.Cache[Name] != null);
 6         }
 7         public static T Get<T>(string Name)
 8         {
 9             if (null != HttpRuntime.Cache[Name]) { return (T)HttpRuntime.Cache[Name]; }
10             return default(T);
11         }
12 
13         public static void Save(string Name, object Value, string FileName, TimeSpan expirese)
14         {
15             var dependency = new CacheDependency(FileName);
16             Save(Name,
17                 Value,
18                 dependency,
19                 expirese);
20         }
21 
22         public static void Save(string Name, object Value)
23         {
24             HttpRuntime.Cache.Insert(Name, Value);
25         }
26 
27         public static void Save(string Name, object Value, CacheDependency Dependency, TimeSpan expirese)
28         {
29             HttpRuntime.Cache.Insert(Name,
30                 Value,
31                 Dependency,
32                 (DateTime.Now + expirese),
33                 System.Web.Caching.Cache.NoSlidingExpiration);
34         }
35     }

3、請求上下文(HttpContextExtension)類

 1 public static class HttpContextExtension
 2     {
 3         /// <summary>
 4         /// 請求上下文
 5         /// </summary>
 6         /// <param name="context"></param>
 7         /// <returns></returns>
 8         public static WeiXinPayConfig GetWeiXinPayConfig(this HttpContextBase context)
 9         {
10             return ApiHelper.GetConfigureSection<WeiXinPayConfig>("WeiXinPay");
11         }
12     }

4、獲取值

 1         /// <summary>
 2         /// 
 3         /// </summary>
 4         private Models.WeiXinPayConfig wxApiConfig { get; set; }
 5         /// <summary>
 6         /// 
 7         /// </summary>
 8         /// <returns></returns>
 9         public ActionResult GetConfig()
10         {
11 
12             wxApiConfig = HttpContext.GetWeiXinPayConfig();
13             
14             return View();
15         }

Asp.Net讀取配置文件