1. 用于獲取或設(shè)置Web.config/*.exe.config中節(jié)點(diǎn)數(shù)據(jù)的輔助類
/**//// <summary>
/// 用于獲取或設(shè)置Web.config/*.exe.config中節(jié)點(diǎn)數(shù)據(jù)的輔助類
/// </summary> public sealed class AppConfig
{
private string filePath;
/**//// <summary>
/// 從當(dāng)前目錄中按順序檢索Web.Config和*.App.Config文件。
/// 如果找到一個(gè),則使用它作為配置文件;否則會(huì)拋出一個(gè)ArgumentNullException異常。
/// </summary>
public AppConfig()
{
string webconfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web.Config");
string appConfig = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Replace(".vshost", "");
if (File.Exists(webconfig))
{
filePath = webconfig;
}
else if (File.Exists(appConfig))
{
filePath = appConfig;
}
else
{
throw new ArgumentNullException("沒(méi)有找到Web.Config文件或者應(yīng)用程序配置文件, 請(qǐng)指定配置文件");
}
}
/**//// <summary>
/// 用戶指定具體的配置文件路徑
/// </summary>
/// <param name="configFilePath">配置文件路徑(絕對(duì)路徑)</param>
public AppConfig(string configFilePath)
{
filePath = configFilePath;
}
/**//// <summary>
/// 設(shè)置程序的config文件
/// </summary>
/// <param name="keyName">鍵名</param>
/// <param name="keyValue">鍵值</param>
public void AppConfigSet(string keyName, string keyValue)
{
//由于存在多個(gè)Add鍵值,使得訪問(wèn)appSetting的操作不成功,故注釋下面語(yǔ)句,改用新的方式
/**//*
string xpath = "http://add[@key='" + keyName + "']";
XmlDocument document = new XmlDocument();
document.Load(filePath);
XmlNode node = document.SelectSingleNode(xpath);
node.Attributes["value"].Value = keyValue;
document.Save(filePath);
*/
XmlDocument document = new XmlDocument();
document.Load(filePath);
XmlNodeList nodes = document.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
//獲得將當(dāng)前元素的key屬性
XmlAttribute attribute = nodes[i].Attributes["key"];
//根據(jù)元素的第一個(gè)屬性來(lái)判斷當(dāng)前的元素是不是目標(biāo)元素
if (attribute != null && (attribute.Value == keyName))
{
attribute = nodes[i].Attributes["value"];
//對(duì)目標(biāo)元素中的第二個(gè)屬性賦值
if (attribute != null)
{
attribute.Value = keyValue;
break;
}
}
}
document.Save(filePath);
}
/**//// <summary>
/// 讀取程序的config文件的鍵值。
/// 如果鍵名不存在,返回空
/// </summary>
/// <param name="keyName">鍵名</param>
/// <returns></returns>
public string AppConfigGet(string keyName)
{
string strReturn = string.Empty;
try
{
XmlDocument document = new XmlDocument();
document.Load(filePath);
XmlNodeList nodes = document.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
//獲得將當(dāng)前元素的key屬性
XmlAttribute attribute = nodes[i].Attributes["key"];
//根據(jù)元素的第一個(gè)屬性來(lái)判斷當(dāng)前的元素是不是目標(biāo)元素
if (attribute != null && (attribute.Value == keyName))
{
attribute = nodes[i].Attributes["value"];
if (attribute != null)
{
strReturn = attribute.Value;
break;
}
}
}
}
catch
{
;
}
return strReturn;
}
/**//// <summary>
/// 獲取指定鍵名中的子項(xiàng)的值
/// </summary>
/// <param name="keyName">鍵名</param>
/// <param name="subKeyName">以分號(hào)(;)為分隔符的子項(xiàng)名稱</param>
/// <returns>對(duì)應(yīng)子項(xiàng)名稱的值(即是=號(hào)后面的值)</returns>
public string GetSubValue(string keyName, string subKeyName)
{
string connectionString = AppConfigGet(keyName).ToLower();
string[] item = connectionString.Split(new char[] {';'});
for (int i = 0; i < item.Length; i++)
{
string itemValue = item[i].ToLower();
if (itemValue.IndexOf(subKeyName.ToLower()) >= 0) //如果含有指定的關(guān)鍵字
{
int startIndex = item[i].IndexOf("="); //等號(hào)開(kāi)始的位置
return item[i].Substring(startIndex + 1); //獲取等號(hào)后面的值即為Value
}
}
return string.Empty;
}
} AppConfig測(cè)試代碼:
public class TestAppConfig
{
public static string Execute()
{
string result = string.Empty;
//讀取Web.Config的
AppConfig config = new AppConfig();
result += "讀取Web.Config中的配置信息:" + "\r\n";
result += config.AppName + "\r\n";
result += config.AppConfigGet("WebConfig") + "\r\n";
config.AppConfigSet("WebConfig", DateTime.Now.ToString("hh:mm:ss"));
result += config.AppConfigGet("WebConfig") + "\r\n\r\n";
//讀取*.App.Config的
config = new AppConfig("TestUtilities.exe.config");
result += "讀取TestUtilities.exe.config中的配置信息:" + "\r\n";
result += config.AppName + "\r\n";
result += config.AppConfigGet("AppConfig") + "\r\n";
config.AppConfigSet("AppConfig", DateTime.Now.ToString("hh:mm:ss"));
result += config.AppConfigGet("AppConfig") + "\r\n\r\n";
return result;
}
} 2. 反射操作輔助類ReflectionUtil
/**//// <summary>
/// 反射操作輔助類
/// </summary> public sealed class ReflectionUtil
{
private ReflectionUtil()
{
}
private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
/**//// <summary>
/// 執(zhí)行某個(gè)方法
/// </summary>
/// <param name="obj">指定的對(duì)象</param>
/// <param name="methodName">對(duì)象方法名稱</param>
/// <param name="args">參數(shù)</param>
/// <returns></returns>
public static object InvokeMethod(object obj, string methodName, object[] args)
{
object objResult = null;
Type type = obj.GetType();
objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
return objResult;
}
/**//// <summary>
/// 設(shè)置對(duì)象字段的值
/// </summary>
public static void SetField(object obj, string name, object value)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
fieldInfo.SetValue(objValue, value);
}
/**//// <summary>
/// 獲取對(duì)象字段的值
/// </summary>
public static object GetField(object obj, string name)
{
FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
return fieldInfo.GetValue(obj);
}
/**//// <summary>
/// 設(shè)置對(duì)象屬性的值
/// </summary>
public static void SetProperty(object obj, string name, object value)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
propertyInfo.SetValue(obj, objValue, null);
}
/**//// <summary>
/// 獲取對(duì)象屬性的值
/// </summary>
public static object GetProperty(object obj, string name)
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
return propertyInfo.GetValue(obj, null);
}
/**//// <summary>
/// 獲取對(duì)象屬性信息(組裝成字符串輸出)
/// </summary>
public static string GetProperties(object obj)
{
StringBuilder strBuilder = new StringBuilder();
PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags);
foreach (PropertyInfo property in propertyInfos)
{
strBuilder.Append(property.Name);
strBuilder.Append(":");
strBuilder.Append(property.GetValue(obj, null));
strBuilder.Append("\r\n");
}
return strBuilder.ToString();
}
} 反射操作輔助類ReflectionUtil測(cè)試代碼:
public class TestReflectionUtil
{
public static string Execute()
{
string result = string.Empty;
result += "使用ReflectionUtil反射操作輔助類:" + "\r\n";
try
{
Person person = new Person();
person.Name = "wuhuacong";
person.Age = 20;
result += DecriptPerson(person);
person.Name = "Wade Wu";
person.Age = 99;
result += DecriptPerson(person);
}
catch (Exception ex)
{
result += string.Format("發(fā)生錯(cuò)誤:{0}!\r\n \r\n", ex.Message);
}
return result;
}
public static string DecriptPerson(Person person)
{
string result = string.Empty;
result += "name:" + ReflectionUtil.GetField(person, "name") + "\r\n";
result += "age" + ReflectionUtil.GetField(person, "age") + "\r\n";
result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "\r\n";
result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "\r\n";
result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "\r\n";
result += "操作完成!\r\n \r\n";
return result;
}
} 3. 注冊(cè)表訪問(wèn)輔助類RegistryHelper
/**//// <summary>
/// 注冊(cè)表訪問(wèn)輔助類
/// </summary> public sealed class RegistryHelper
{
private string softwareKey = string.Empty;
private RegistryKey rootRegistry = Registry.CurrentUser;
/**//// <summary>
/// 使用注冊(cè)表鍵構(gòu)造,默認(rèn)從Registry.CurrentUser開(kāi)始。
/// </summary>
/// <param name="softwareKey">注冊(cè)表鍵,格式如"SOFTWARE\\Huaweisoft\\EDNMS"的字符串</param>
public RegistryHelper(string softwareKey) : this(softwareKey, Registry.CurrentUser)
{
}
/**//// <summary>
/// 指定注冊(cè)表鍵及開(kāi)始的根節(jié)點(diǎn)查詢
/// </summary>
/// <param name="softwareKey">注冊(cè)表鍵</param>
/// <param name="rootRegistry">開(kāi)始的根節(jié)點(diǎn)(Registry.CurrentUser或者Registry.LocalMachine等)</param>
public RegistryHelper(string softwareKey, RegistryKey rootRegistry)
{
this.softwareKey = softwareKey;
this.rootRegistry = rootRegistry;
}
/**//// <summary>
/// 根據(jù)注冊(cè)表的鍵獲取鍵值。
/// 如果注冊(cè)表的鍵不存在,返回空字符串。
/// </summary>
/// <param name="key">注冊(cè)表的鍵</param>
/// <returns>鍵值</returns>
public string GetValue(string key)
{
const string parameter = "key";
if (null == key)
{
throw new ArgumentNullException(parameter);
}
string result = string.Empty;
try
{
RegistryKey registryKey = rootRegistry.OpenSubKey(softwareKey);
result = registryKey.GetValue(key).ToString();
}
catch
{
;
}
return result;
}
/**//// <summary>
/// 保存注冊(cè)表的鍵值
/// </summary>
/// <param name="key">注冊(cè)表的鍵</param>
/// <param name="value">鍵值</param>
/// <returns>成功返回true,否則返回false.</returns>
public bool SaveValue(string key, string value)
{
const string parameter1 = "key";
const string parameter2 = "value";
if (null == key)
{
throw new ArgumentNullException(parameter1);
}
if (null == value)
{
throw new ArgumentNullException(parameter2);
}
RegistryKey registryKey = rootRegistry.OpenSubKey(softwareKey, true);
if (null == registryKey)
{
registryKey = rootRegistry.CreateSubKey(softwareKey);
}
registryKey.SetValue(key, value);
return true;
}
} 注冊(cè)表訪問(wèn)輔助類RegistryHelper測(cè)試代碼:
360docimg_501_ public class TestRegistryHelper
360docimg_502_360docimg_503_ 360docimg_504_{
360docimg_505_ public static string Execute()
360docimg_506_360docimg_507_ 360docimg_508_{
360docimg_509_ string result = string.Empty;
360docimg_510_ result += "使用RegistryHelper注冊(cè)表訪問(wèn)輔助類:" + "\r\n";
360docimg_511_
360docimg_512_ RegistryHelper registry = new RegistryHelper("SoftWare\\HuaweiSoft\\EDNMS");
360docimg_513_ bool sucess = registry.SaveValue("Test", DateTime.Now.ToString("hh:mm:ss"));
360docimg_514_ if (sucess)
360docimg_515_360docimg_516_ 360docimg_517_{
360docimg_518_ result += registry.GetValue("Test");
360docimg_519_ }
360docimg_520_
360docimg_521_ return result;
360docimg_522_ }
360docimg_523_ }
4. 壓縮/解壓縮輔助類ZipUtil
360docimg_524_360docimg_525_ /**//// <summary>
360docimg_526_ /// 壓縮/解壓縮輔助類
360docimg_527_ /// </summary>
360docimg_528_ public sealed class ZipUtil
360docimg_529_360docimg_530_ 360docimg_531_{
360docimg_532_ private ZipUtil()
360docimg_533_360docimg_534_ 360docimg_535_{
360docimg_536_ }
360docimg_537_
360docimg_538_360docimg_539_ /**//// <summary>
360docimg_540_ /// 壓縮文件操作
360docimg_541_ /// </summary>
360docimg_542_ /// <param name="fileToZip">待壓縮文件名</param>
360docimg_543_ /// <param name="zipedFile">壓縮后的文件名</param>
360docimg_544_ /// <param name="compressionLevel">0~9,表示壓縮的程度,9表示最高壓縮</param>
360docimg_545_ /// <param name="blockSize">緩沖塊大小</param>
360docimg_546_ public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
360docimg_547_360docimg_548_ 360docimg_549_{
360docimg_550_ if (! File.Exists(fileToZip))
360docimg_551_360docimg_552_ 360docimg_553_{
360docimg_554_ throw new FileNotFoundException("文件 " + fileToZip + " 沒(méi)有找到,取消壓縮。");
360docimg_555_ }
360docimg_556_
360docimg_557_ using (FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
360docimg_558_360docimg_559_ 360docimg_560_{
360docimg_561_ FileStream fileStream = File.Create(zipedFile);
360docimg_562_ using (ZipOutputStream zipStream = new ZipOutputStream(fileStream))
360docimg_563_360docimg_564_ 360docimg_565_{
360docimg_566_ ZipEntry zipEntry = new ZipEntry(fileToZip);
360docimg_567_ zipStream.PutNextEntry(zipEntry);
360docimg_568_ zipStream.SetLevel(compressionLevel);
360docimg_569_
360docimg_570_ byte[] buffer = new byte[blockSize];
360docimg_571_ Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
360docimg_572_ zipStream.Write(buffer, 0, size);
360docimg_573_
360docimg_574_ try
360docimg_575_360docimg_576_ 360docimg_577_{
360docimg_578_ while (size < streamToZip.Length)
360docimg_579_360docimg_580_ 360docimg_581_{
360docimg_582_ int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
360docimg_583_ zipStream.Write(buffer, 0, sizeRead);
360docimg_584_ size += sizeRead;
360docimg_585_ }
360docimg_586_ }
360docimg_587_ catch (Exception ex)
360docimg_588_360docimg_589_ 360docimg_590_{
360docimg_591_ throw ex;
360docimg_592_ }
360docimg_593_ zipStream.Finish();
360docimg_594_ }
360docimg_595_ }
360docimg_596_ }
360docimg_597_
360docimg_598_360docimg_599_ /**//// <summary>
360docimg_600_ /// 打開(kāi)sourceZipPath的壓縮文件,解壓到destPath目錄中
360docimg_601_ /// </summary>
360docimg_602_ /// <param name="sourceZipPath">待解壓的文件路徑</param>
360docimg_603_ /// <param name="destPath">解壓后的文件路徑</param>
360docimg_604_ public static void UnZipFile(string sourceZipPath, string destPath)
360docimg_605_360docimg_606_ 360docimg_607_{
360docimg_608_ if (!destPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
360docimg_609_360docimg_610_ 360docimg_611_{
360docimg_612_ destPath = destPath + Path.DirectorySeparatorChar;
360docimg_613_ }
360docimg_614_
360docimg_615_ using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(sourceZipPath)))
360docimg_616_360docimg_617_ 360docimg_618_{
360docimg_619_ ZipEntry theEntry;
360docimg_620_ while ((theEntry = zipInputStream.GetNextEntry()) != null)
360docimg_621_360docimg_622_ 360docimg_623_{
360docimg_624_ string fileName = destPath + Path.GetDirectoryName(theEntry.Name) +
360docimg_625_ Path.DirectorySeparatorChar + Path.GetFileName(theEntry.Name);
360docimg_626_
360docimg_627_ //create directory for file (if necessary)
360docimg_628_ Directory.CreateDirectory(Path.GetDirectoryName(fileName));
360docimg_629_
360docimg_630_ if (!theEntry.IsDirectory)
360docimg_631_360docimg_632_ 360docimg_633_{
360docimg_634_ using (FileStream streamWriter = File.Create(fileName))
360docimg_635_360docimg_636_ 360docimg_637_{
360docimg_638_ int size = 2048;
360docimg_639_ byte[] data = new byte[size];
360docimg_640_ try
360docimg_641_360docimg_642_ 360docimg_643_{
360docimg_644_ while (true)
360docimg_645_360docimg_646_ 360docimg_647_{
360docimg_648_ size = zipInputStream.Read(data, 0, data.Length);
360docimg_649_ if (size > 0)
360docimg_650_360docimg_651_ 360docimg_652_{
360docimg_653_ streamWriter.Write(data, 0, size);
360docimg_654_ }
360docimg_655_ else
360docimg_656_360docimg_657_ 360docimg_658_{
360docimg_659_ break;
360docimg_660_ }
360docimg_661_ }
360docimg_662_ }
360docimg_663_ catch
360docimg_664_360docimg_665_ 360docimg_666_{
360docimg_667_ }
360docimg_668_ }
360docimg_669_ }
360docimg_670_ }
360docimg_671_ }
360docimg_672_ }
360docimg_673_ }
壓縮/解壓縮輔助類ZipUtil測(cè)試代碼:
360docimg_674_ public class TestZipUtil
360docimg_675_360docimg_676_ 360docimg_677_{
360docimg_678_ public static string Execute()
360docimg_679_360docimg_680_ 360docimg_681_{
360docimg_682_ string result = string.Empty;
360docimg_683_ result += "使用ZipUtil壓縮/解壓縮輔助類:" + "\r\n";
360docimg_684_
360docimg_685_ try
360docimg_686_360docimg_687_ 360docimg_688_{
360docimg_689_ ZipUtil.ZipFile("Web.Config", "Test.Zip", 6, 512);
360docimg_690_ ZipUtil.UnZipFile("Test.Zip", "Test");
360docimg_691_
360docimg_692_ result += "操作完成!\r\n \r\n";
360docimg_693_ }
360docimg_694_ catch (Exception ex)
360docimg_695_360docimg_696_ 360docimg_697_{
360docimg_698_ result += string.Format("發(fā)生錯(cuò)誤:{0}!\r\n \r\n", ex.Message);
360docimg_699_ }
360docimg_700_ return result;
360docimg_701_ }
360docimg_702_ }