天天看點

.NET開發不可不知、不可不用的輔助類(一)

1. 用于擷取或設定Web.config/*.exe.config中節點資料的輔助類

/// <summary>
    /// 用于擷取或設定Web.config/*.exe.config中節點資料的輔助類
    /// </summary>
    public sealed class AppConfig
    {
        private string filePath;

        /// <summary>
        /// 從目前目錄中按順序檢索Web.Config和*.App.Config檔案。
        /// 如果找到一個,則使用它作為配置檔案;否則會抛出一個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("沒有找到Web.Config檔案或者應用程式配置檔案, 請指定配置檔案");
            }
        }


        /// <summary>
        /// 使用者指定具體的配置檔案路徑
        /// </summary>
        /// <param name="configFilePath">配置檔案路徑(絕對路徑)</param>
        public AppConfig(string configFilePath)
        {
            filePath = configFilePath;
        }

        /// <summary>
        /// 設定程式的config檔案
        /// </summary>
        /// <param name="keyName">鍵名</param>
        /// <param name="keyValue">鍵值</param>
        public void AppConfigSet(string keyName, string keyValue)
        {
            //由于存在多個Add鍵值,使得通路appSetting的操作不成功,故注釋下面語句,改用新的方式
            /* 
            string xpath = "//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++)
            {
                //獲得将目前元素的key屬性
                XmlAttribute attribute = nodes[i].Attributes["key"];
                //根據元素的第一個屬性來判斷目前的元素是不是目标元素
                if (attribute != null && (attribute.Value == keyName))
                {
                    attribute = nodes[i].Attributes["value"];
                    //對目标元素中的第二個屬性指派
                    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++)
                {
                    //獲得将目前元素的key屬性
                    XmlAttribute attribute = nodes[i].Attributes["key"];
                    //根據元素的第一個屬性來判斷目前的元素是不是目标元素
                    if (attribute != null && (attribute.Value == keyName))
                    {
                        attribute = nodes[i].Attributes["value"];
                        if (attribute != null)
                        {
                            strReturn = attribute.Value;
                            break;
                        }
                    }
                }
            }
            catch
            {
                ;
            }

            return strReturn;
        }

        /// <summary>
        /// 擷取指定鍵名中的子項的值
        /// </summary>
        /// <param name="keyName">鍵名</param>
        /// <param name="subKeyName">以分号(;)為分隔符的子項名稱</param>
        /// <returns>對應子項名稱的值(即是=号後面的值)</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) //如果含有指定的關鍵字
                {
                    int startIndex = item[i].IndexOf("="); //等号開始的位置
                    return item[i].Substring(startIndex + 1); //擷取等号後面的值即為Value
                }
            }
            return string.Empty;
        }
}
           

AppConfig測試代碼:

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>
        /// 執行某個方法
        /// </summary>
        /// <param name="obj">指定的對象</param>
        /// <param name="methodName">對象方法名稱</param>
        /// <param name="args">參數</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>
        /// 設定對象字段的值
        /// </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>
        /// 擷取對象字段的值
        /// </summary>
        public static object GetField(object obj, string name)
        {
            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
            return fieldInfo.GetValue(obj);
        }

        /// <summary>
        /// 設定對象屬性的值
        /// </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>
        /// 擷取對象屬性的值
        /// </summary>
        public static object GetProperty(object obj, string name)
        {
            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
            return propertyInfo.GetValue(obj, null);
        }

        /// <summary>
        /// 擷取對象屬性資訊(組裝成字元串輸出)
        /// </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測試代碼:

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("發生錯誤:{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. 系統資料庫通路輔助類RegistryHelper

/// <summary>
    /// 系統資料庫通路輔助類
    /// </summary>
    public sealed class RegistryHelper
    {
        private string softwareKey = string.Empty;
        private RegistryKey rootRegistry = Registry.CurrentUser;

        /// <summary>
        /// 使用系統資料庫鍵構造,預設從Registry.CurrentUser開始。
        /// </summary>
        /// <param name="softwareKey">系統資料庫鍵,格式如"SOFTWARE\\Huaweisoft\\EDNMS"的字元串</param>
        public RegistryHelper(string softwareKey) : this(softwareKey, Registry.CurrentUser)
        {
        }

        /// <summary>
        /// 指定系統資料庫鍵及開始的根節點查詢
        /// </summary>
        /// <param name="softwareKey">系統資料庫鍵</param>
        /// <param name="rootRegistry">開始的根節點(Registry.CurrentUser或者Registry.LocalMachine等)</param>
        public RegistryHelper(string softwareKey, RegistryKey rootRegistry)
        {
            this.softwareKey = softwareKey;
            this.rootRegistry = rootRegistry;
        }


        /// <summary>
        /// 根據系統資料庫的鍵擷取鍵值。
        /// 如果系統資料庫的鍵不存在,傳回空字元串。
        /// </summary>
        /// <param name="key">系統資料庫的鍵</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>
        /// 儲存系統資料庫的鍵值
        /// </summary>
        /// <param name="key">系統資料庫的鍵</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;
        }
    }
           

系統資料庫通路輔助類RegistryHelper測試代碼:

public class TestRegistryHelper
    {
        public static string Execute()
        {
            string result = string.Empty;
            result += "使用RegistryHelper系統資料庫通路輔助類:" + "\r\n";

            RegistryHelper registry = new RegistryHelper("SoftWare\\HuaweiSoft\\EDNMS");
            bool sucess = registry.SaveValue("Test", DateTime.Now.ToString("hh:mm:ss"));
            if (sucess)
            {
                result += registry.GetValue("Test");
            }

            return result;
        }
    }
           

4. 壓縮/解壓縮輔助類ZipUtil

/// <summary>
    /// 壓縮/解壓縮輔助類
    /// </summary>
    public sealed class ZipUtil
    {
        private ZipUtil()
        {
        }

        /// <summary>
        /// 壓縮檔案操作
        /// </summary>
        /// <param name="fileToZip">待壓縮檔案名</param>
        /// <param name="zipedFile">壓縮後的檔案名</param>
        /// <param name="compressionLevel">0~9,表示壓縮的程度,9表示最高壓縮</param>
        /// <param name="blockSize">緩沖塊大小</param>
        public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
        {
            if (! File.Exists(fileToZip))
            {
                throw new FileNotFoundException("檔案 " + fileToZip + " 沒有找到,取消壓縮。");
            }

            using (FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
            {
                FileStream fileStream = File.Create(zipedFile);
                using (ZipOutputStream zipStream = new ZipOutputStream(fileStream))
                {
                    ZipEntry zipEntry = new ZipEntry(fileToZip);
                    zipStream.PutNextEntry(zipEntry);
                    zipStream.SetLevel(compressionLevel);

                    byte[] buffer = new byte[blockSize];
                    Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
                    zipStream.Write(buffer, 0, size);

                    try
                    {
                        while (size < streamToZip.Length)
                        {
                            int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, sizeRead);
                            size += sizeRead;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    zipStream.Finish();
                }
            }
        }

        /// <summary>
        /// 打開sourceZipPath的壓縮檔案,解壓到destPath目錄中
        /// </summary>
        /// <param name="sourceZipPath">待解壓的檔案路徑</param>
        /// <param name="destPath">解壓後的檔案路徑</param>
        public static void UnZipFile(string sourceZipPath, string destPath)
        {
            if (!destPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                destPath = destPath + Path.DirectorySeparatorChar;
            }

            using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(sourceZipPath)))
            {
                ZipEntry theEntry;
                while ((theEntry = zipInputStream.GetNextEntry()) != null)
                {
                    string fileName = destPath + Path.GetDirectoryName(theEntry.Name) +
                        Path.DirectorySeparatorChar + Path.GetFileName(theEntry.Name);

                    //create directory for file (if necessary)
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                    if (!theEntry.IsDirectory)
                    {
                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[size];
                            try
                            {
                                while (true)
                                {
                                    size = zipInputStream.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }
    }
           

壓縮/解壓縮輔助類ZipUtil測試代碼:

public class TestZipUtil
    {
        public static string Execute()
        {
            string result = string.Empty;
            result += "使用ZipUtil壓縮/解壓縮輔助類:" + "\r\n";

            try
            {
                ZipUtil.ZipFile("Web.Config", "Test.Zip", 6, 512);
                ZipUtil.UnZipFile("Test.Zip", "Test");

                result += "操作完成!\r\n \r\n";
            }
            catch (Exception ex)
            {
                result += string.Format("發生錯誤:{0}!\r\n \r\n", ex.Message);
            }
            return result;
        }
    }
           

============================

聲明:本文是轉載過來的,由于時間過去太久已經找不到原文連結了,如有知道原文連結的麻煩告知一下。另外如有侵權請聯系我更改或删除,謝謝。