當前位置:
首頁 > 知識 > Asp.Net 常用工具類---Config操作(7)

Asp.Net 常用工具類---Config操作(7)

近期工作比較忙,忙到忘記寫博客(自己的借口,主要加班下班後不想動)。

月初的時候,打算每兩天寫一篇博文,分享自己的一些心得和開發體驗,無奈現在只寫到第六篇,然而時間已經是20號,歲月不饒人!

總想寫點什麼,但是有時候文筆可能不咋樣,排版也不是很講究,寫的碎碎的。

雖然閱讀量、推薦量不高,但是我感覺做事就要持之以恆,保持分享精神

上一篇寫了一些office的操作,包括excel word html pdf,現在想想,確實有點粗糙,不夠精鍊。

今天準備寫一篇關於config文件的基本操作,包括:鏈接字元串,appSettings操作,運行地址等等。

大家都知道,有時候一些sdk信息賬戶為了可配置化,除了存庫以外,webconfig的配置更能方便簡介,且容易維護!

下面貼出我的幫助類(借鑒了cyqdata的幫助類,然後做了一些修改):

using System;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Reflection;

namespace Utils.Config
{
///

/// 配置文件
///

public static class Config
{
///

/// 配置字典
///

public static readonly Dictionary Configs = new Dictionary(StringComparer.OrdinalIgnoreCase);

///

/// 鏈接字元串配置字典
///

public static readonly Dictionary ConnConfigs = new Dictionary(StringComparer.OrdinalIgnoreCase);

///

/// 文件路徑前綴
///

public const string FilePre = "file:";

///

/// 框架的運行路徑
///

public static string RunfolderPath;

///

/// 框架程序集名稱
///

public static string DllFullName;

///

/// 鏈接字元串
///

public static string _defaultConn;

///

/// 獲取當前Dll的版本號
///

public static string Version => Assembly.GetExecutingAssembly.GetName.Version.ToString;

///

/// Web根目錄
///

public static string WebRootPath => AppDomain.CurrentDomain.BaseDirectory;

///

/// 瀏覽器地址 (協議名+域名+站點名+文件名+參數)
///

public static Uri WebUr => HttpContext.Current.Request.Url;

///

/// 框架的運行路徑
///

public static string RunPath
{
get
{
if (string.IsNullOrEmpty(RunfolderPath))
{
Assembly ass = Assembly.GetExecutingAssembly;
DllFullName = ass.FullName;
RunfolderPath = ass.CodeBase;
RunfolderPath = System.IO.Path.GetDirectoryName(RunfolderPath).Replace(FilePre, string.Empty) + "";
}
return RunfolderPath;
}
}

///

/// 設置Web.config或App.config的值。
///

public static void SetApp(string key, string value)
{
try
{
if (Configs.ContainsKey(key))
Configs[key] = value;
else
Configs.Add(key, value);
}
catch (Exception err)
{
Log.Log.Txt(err);
}
}
///

/// 獲取Web.config或App.config的值。
///

public static string GetApp(string key)
{
return GetApp(key, string.Empty);
}

///

/// 獲取Web.config或App.config的值(允許值不存在或為空時輸出默認值)。
///

public static string GetApp(string key, string defaultValue, string filepath = "")
{
if (Configs.ContainsKey(key))
return Configs[key];
else if (!string.IsNullOrEmpty(filepath))
{
ExeConfigurationFileMap ecf = new ExeConfigurationFileMap;
ecf.ExeConfigFilename = filepath;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
return config.AppSettings.Settings[key].Value;
}
else
{
string value = ConfigurationManager.AppSettings[key];
value = string.IsNullOrEmpty(value) ? defaultValue : value;
try
{
Configs.Add(key, value);
}
catch (Exception err)
{
Log.Log.Txt(err);
}
return value;
}
}

///

/// 獲取Web.config或App.config的數字值(允許值不存在或為空時輸出默認值)。
///

public static int GetAppInt(string key, int defaultValue)
{
int result;
string value = GetApp(key);
if (!int.TryParse(value, out result))
return defaultValue;
return result;
}

///

/// 獲取Web.config或App.config的數字值(允許值不存在或為空時輸出默認值)。
///

public static bool GetAppBool(string key, bool defaultValue)
{
bool result;
bool.TryParse(GetApp(key, defaultValue.ToString), out result);
return result;
}

///

/// 獲取Web.config或App.config的connectionStrings節點的值。
///

public static string GetConn(string name, out string providerName)
{
providerName = string.Empty;
if (string.IsNullOrEmpty(name))
name = "Default";
if (name.Trim.Contains(" "))
return name;
if (ConnConfigs.ContainsKey(name))
return ConnConfigs[name];
ConnectionStringSettings conn = ConfigurationManager.ConnectionStrings[name];
if (conn != null)
{
providerName = conn.ProviderName;
if (name == conn.ConnectionString)//避免誤寫自己造成死循環。
return name;
name = conn.ConnectionString;
if (!string.IsNullOrEmpty(name) && name.Length < 32 && name.Split(" ").Length == 1) return GetConn(name); if (!ConnConfigs.ContainsKey(name) && string.IsNullOrEmpty(providerName)) // 如果有providerName,則不存檔 ConnConfigs.Add(name, conn.ConnectionString); return conn.ConnectionString; } if (name.Length > 32 && name.Split("=").Length > 3 && name.Contains(";")) //鏈接字元串很長,沒空格的情況
return name;
return "";
}

///

/// 獲取Web.config或App.config的connectionStrings節點的值。
///

public static string GetConn(string name)
{
string p;
return GetConn(name, out p);
}

///

/// 添加自定義鏈接(內存有效,並未寫入config文件)
///

/// 名稱 /// 鏈接字元串 public static void SetConn(string name, string connectionString)
{
if (!ConnConfigs.ContainsKey(name))
ConnConfigs.Add(name, connectionString);
else
ConnConfigs[name] = connectionString;
}

///

/// 獲取URL
///

public static string Url
{
get
{
string pageUrl = string.Empty;
if (HttpContext.Current != null)
{
HttpRequest request = HttpContext.Current.Request;
if (request.UrlReferrer != null && request.Url != request.UrlReferrer)
pageUrl = request.Url.Scheme + "://" + request.Url.Authority + request.RawUrl + request.UrlReferrer;
else
pageUrl = request.Url.Scheme + "://" + request.Url.Authority + request.RawUrl;
}
return pageUrl;
}
}

///

/// 資料庫鏈接字元串
///

public static string DefaultConn
{
get
{
if (string.IsNullOrEmpty(_defaultConn))
{
_defaultConn = "Defalut";
if (ConfigurationManager.ConnectionStrings != null && ConfigurationManager.ConnectionStrings[_defaultConn] == null)
{
foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings)
{
if (item.Name.ToLower.EndsWith("Defalut"))
{
_defaultConn = item.Name;
break;
}
}
}
}

return _defaultConn;
}
set
{
if (value == null)
value = string.Empty;
_defaultConn = value;

}
}

///

/// 生成一個文件夾路徑
///

/// 文件夾名稱 /// config配置key public static string GenerateFilePath(string foldername, string configkey = "")
{
string path = GetApp(configkey, foldername);
if (!path.EndsWith(""))
path = path.TrimEnd("/");
if (path.StartsWith("~/"))
path = path.Substring(2);

string folder = Config.WebRootPath;
folder = folder + path + @"";

if (!System.IO.Directory.Exists(folder))
System.IO.Directory.CreateDirectory(folder);
return folder;
}
}
}

OK,各位看官,這一期的文章config操作寫到這裡喏,感謝大家的支持,您的支持是我的動力!

下一期給大家帶來的是常用的Log幫助類,敬請期待!!!

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 達人科技 的精彩文章:

實現一個Android電子書閱讀APP
JVM類載入過程 & 雙親委派模型
Java 的泛型擦除和運行時泛型信息獲取
0基礎搭建Hadoop大數據處理-環境
關於微信和支付寶自動退款介面的接入總結

TAG:達人科技 |

您可能感興趣

推薦:幫助賣家贏得亞馬遜「buy box」的5款常用工具
數字貨幣常用工具火幣pro
從小白變RSA大神,附常用工具使用方法及CTF中RSA典型例題
pick這3個口語滿分大神常用工具,不做托福口語「菊外人」
叨叨手工DIY常用工具
JS 開發常用工具函數
PC性能怎麼看?常用工具軟體一覽
木作常用工具
你知道3D列印都有哪些常用工具嗎?
家庭訓犬的常用工具
毛絨玩具設計常用工具介紹
水彩畫常用工具介紹
培育果樹盆景常用工具有哪些?新手必看,至少5遍!
美國網民:為什麼筷子是吃中餐的常用工具,他們不覺的這很辛苦?
搓澡搓出皮膚癌,2種常用工具卻是幫凶?皮膚科醫生說出了真相
妲己發明了一種刑具,受刑者比死還難受,如今已成為婦女常用工具