当前位置: 首页 > news >正文

.NET开发不可不知、不可不用的辅助类(一)

1. 用于获取或设置Web.config/*.exe.config中节点数据的辅助类
ExpandedBlockStart.gif     /// <summary>
InBlock.gif    
/// 用于获取或设置Web.config/*.exe.config中节点数据的辅助类
ExpandedBlockEnd.gif    
/// </summary>
None.gif     public  sealed  class AppConfig
ExpandedBlockStart.gif     {
InBlock.gif        private string filePath;
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 从当前目录中按顺序检索Web.Config和*.App.Config文件。
InBlock.gif        
/// 如果找到一个,则使用它作为配置文件;否则会抛出一个ArgumentNullException异常。
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public AppConfig()
ExpandedSubBlockStart.gif        {
InBlock.gif            string webconfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web.Config");
InBlock.gif            string appConfig = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Replace(".vshost", "");
InBlock.gif
InBlock.gif            if (File.Exists(webconfig))
ExpandedSubBlockStart.gif            {
InBlock.gif                filePath = webconfig;
ExpandedSubBlockEnd.gif            }
InBlock.gif            else if (File.Exists(appConfig))
ExpandedSubBlockStart.gif            {
InBlock.gif                filePath = appConfig;
ExpandedSubBlockEnd.gif            }
InBlock.gif            else
ExpandedSubBlockStart.gif            {
InBlock.gif                throw new ArgumentNullException("没有找到Web.Config文件或者应用程序配置文件, 请指定配置文件");
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 用户指定具体的配置文件路径
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="configFilePath">配置文件路径(绝对路径)</param>
InBlock.gif        public AppConfig(string configFilePath)
ExpandedSubBlockStart.gif        {
InBlock.gif            filePath = configFilePath;
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 设置程序的config文件
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="keyName">键名</param>
ExpandedSubBlockEnd.gif        
/// <param name="keyValue">键值</param>
InBlock.gif        public void AppConfigSet(string keyName, string keyValue)
ExpandedSubBlockStart.gif        {
InBlock.gif            //由于存在多个Add键值,使得访问appSetting的操作不成功,故注释下面语句,改用新的方式
ExpandedSubBlockStart.gif
            /* 
InBlock.gif            string xpath = "//add[@key='" + keyName + "']";
InBlock.gif            XmlDocument document = new XmlDocument();
InBlock.gif            document.Load(filePath);
InBlock.gif
InBlock.gif            XmlNode node = document.SelectSingleNode(xpath);
InBlock.gif            node.Attributes["value"].Value = keyValue;
InBlock.gif            document.Save(filePath); 
ExpandedSubBlockEnd.gif             
*/
InBlock.gif
InBlock.gif            XmlDocument document = new XmlDocument();
InBlock.gif            document.Load(filePath);
InBlock.gif
InBlock.gif            XmlNodeList nodes = document.GetElementsByTagName("add");
InBlock.gif            for (int i = 0; i < nodes.Count; i++)
ExpandedSubBlockStart.gif            {
InBlock.gif                //获得将当前元素的key属性
InBlock.gif
                XmlAttribute attribute = nodes[i].Attributes["key"];
InBlock.gif                //根据元素的第一个属性来判断当前的元素是不是目标元素
InBlock.gif
                if (attribute != null && (attribute.Value == keyName))
ExpandedSubBlockStart.gif                {
InBlock.gif                    attribute = nodes[i].Attributes["value"];
InBlock.gif                    //对目标元素中的第二个属性赋值
InBlock.gif
                    if (attribute != null)
ExpandedSubBlockStart.gif                    {
InBlock.gif                        attribute.Value = keyValue;
InBlock.gif                        break;
ExpandedSubBlockEnd.gif                    }
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockEnd.gif            }
InBlock.gif            document.Save(filePath);
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 读取程序的config文件的键值。
InBlock.gif        
/// 如果键名不存在,返回空
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="keyName">键名</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>
InBlock.gif        public string AppConfigGet(string keyName)
ExpandedSubBlockStart.gif        {
InBlock.gif            string strReturn = string.Empty;
InBlock.gif            try
ExpandedSubBlockStart.gif            {
InBlock.gif                XmlDocument document = new XmlDocument();
InBlock.gif                document.Load(filePath);
InBlock.gif
InBlock.gif                XmlNodeList nodes = document.GetElementsByTagName("add");
InBlock.gif                for (int i = 0; i < nodes.Count; i++)
ExpandedSubBlockStart.gif                {
InBlock.gif                    //获得将当前元素的key属性
InBlock.gif
                    XmlAttribute attribute = nodes[i].Attributes["key"];
InBlock.gif                    //根据元素的第一个属性来判断当前的元素是不是目标元素
InBlock.gif
                    if (attribute != null && (attribute.Value == keyName))
ExpandedSubBlockStart.gif                    {
InBlock.gif                        attribute = nodes[i].Attributes["value"];
InBlock.gif                        if (attribute != null)
ExpandedSubBlockStart.gif                        {
InBlock.gif                            strReturn = attribute.Value;
InBlock.gif                            break;
ExpandedSubBlockEnd.gif                        }
ExpandedSubBlockEnd.gif                    }
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockEnd.gif            }
InBlock.gif            catch
ExpandedSubBlockStart.gif            {
InBlock.gif                ;
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            return strReturn;
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 获取指定键名中的子项的值
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="keyName">键名</param>
InBlock.gif        
/// <param name="subKeyName">以分号(;)为分隔符的子项名称</param>
ExpandedSubBlockEnd.gif        
/// <returns>对应子项名称的值(即是=号后面的值)</returns>
InBlock.gif        public string GetSubValue(string keyName, string subKeyName)
ExpandedSubBlockStart.gif        {
InBlock.gif            string connectionString = AppConfigGet(keyName).ToLower();
ExpandedSubBlockStart.gif            string[] item = connectionString.Split(new char[] {';'});
InBlock.gif
InBlock.gif            for (int i = 0; i < item.Length; i++)
ExpandedSubBlockStart.gif            {
InBlock.gif                string itemValue = item[i].ToLower();
InBlock.gif                if (itemValue.IndexOf(subKeyName.ToLower()) >= 0) //如果含有指定的关键字
ExpandedSubBlockStart.gif
                {
InBlock.gif                    int startIndex = item[i].IndexOf("="); //等号开始的位置
InBlock.gif
                    return item[i].Substring(startIndex + 1); //获取等号后面的值即为Value
ExpandedSubBlockEnd.gif
                }
ExpandedSubBlockEnd.gif            }
InBlock.gif            return string.Empty;
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif}
AppConfig测试代码:
None.gif     public  class TestAppConfig
ExpandedBlockStart.gif     {
InBlock.gif        public static string Execute()
ExpandedSubBlockStart.gif        {
InBlock.gif            string result = string.Empty;
InBlock.gif
InBlock.gif            //读取Web.Config的
InBlock.gif
            AppConfig config = new AppConfig();
InBlock.gif            result += "读取Web.Config中的配置信息:" + "\r\n";
InBlock.gif            result += config.AppName + "\r\n";
InBlock.gif            result += config.AppConfigGet("WebConfig") + "\r\n";
InBlock.gif
InBlock.gif            config.AppConfigSet("WebConfig", DateTime.Now.ToString("hh:mm:ss"));
InBlock.gif            result += config.AppConfigGet("WebConfig") + "\r\n\r\n";
InBlock.gif
InBlock.gif
InBlock.gif            //读取*.App.Config的
InBlock.gif
            config = new AppConfig("TestUtilities.exe.config");
InBlock.gif            result += "读取TestUtilities.exe.config中的配置信息:" + "\r\n";
InBlock.gif            result += config.AppName + "\r\n";
InBlock.gif            result += config.AppConfigGet("AppConfig") + "\r\n";
InBlock.gif
InBlock.gif            config.AppConfigSet("AppConfig", DateTime.Now.ToString("hh:mm:ss"));
InBlock.gif            result += config.AppConfigGet("AppConfig") + "\r\n\r\n";
InBlock.gif
InBlock.gif
InBlock.gif            return result;
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
2. 反射操作辅助类ReflectionUtil
ExpandedBlockStart.gif     /// <summary>
InBlock.gif    
/// 反射操作辅助类
ExpandedBlockEnd.gif    
/// </summary>
None.gif     public  sealed  class ReflectionUtil
ExpandedBlockStart.gif     {
InBlock.gif        private ReflectionUtil()
ExpandedSubBlockStart.gif        {
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        private static BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public |
InBlock.gif                                                   BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 执行某个方法
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="obj">指定的对象</param>
InBlock.gif        
/// <param name="methodName">对象方法名称</param>
InBlock.gif        
/// <param name="args">参数</param>
ExpandedSubBlockEnd.gif        
/// <returns></returns>
InBlock.gif        public static object InvokeMethod(object obj, string methodName, object[] args)
ExpandedSubBlockStart.gif        {
InBlock.gif            object objResult = null;
InBlock.gif            Type type = obj.GetType();
InBlock.gif            objResult = type.InvokeMember(methodName, bindingFlags | BindingFlags.InvokeMethod, null, obj, args);
InBlock.gif            return objResult;
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 设置对象字段的值
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public static void SetField(object obj, string name, object value)
ExpandedSubBlockStart.gif        {
InBlock.gif            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
InBlock.gif            object objValue = Convert.ChangeType(value, fieldInfo.FieldType);
InBlock.gif            fieldInfo.SetValue(objValue, value);
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 获取对象字段的值
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public static object GetField(object obj, string name)
ExpandedSubBlockStart.gif        {
InBlock.gif            FieldInfo fieldInfo = obj.GetType().GetField(name, bindingFlags);
InBlock.gif            return fieldInfo.GetValue(obj);
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 设置对象属性的值
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public static void SetProperty(object obj, string name, object value)
ExpandedSubBlockStart.gif        {
InBlock.gif            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
InBlock.gif            object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
InBlock.gif            propertyInfo.SetValue(obj, objValue, null);
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 获取对象属性的值
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public static object GetProperty(object obj, string name)
ExpandedSubBlockStart.gif        {
InBlock.gif            PropertyInfo propertyInfo = obj.GetType().GetProperty(name, bindingFlags);
InBlock.gif            return propertyInfo.GetValue(obj, null);
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 获取对象属性信息(组装成字符串输出)
ExpandedSubBlockEnd.gif        
/// </summary>
InBlock.gif        public static string GetProperties(object obj)
ExpandedSubBlockStart.gif        {
InBlock.gif            StringBuilder strBuilder = new StringBuilder();
InBlock.gif            PropertyInfo[] propertyInfos = obj.GetType().GetProperties(bindingFlags);
InBlock.gif
InBlock.gif            foreach (PropertyInfo property in propertyInfos)
ExpandedSubBlockStart.gif            {
InBlock.gif                strBuilder.Append(property.Name);
InBlock.gif                strBuilder.Append(":");
InBlock.gif                strBuilder.Append(property.GetValue(obj, null));
InBlock.gif                strBuilder.Append("\r\n");
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            return strBuilder.ToString();
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
反射操作辅助类ReflectionUtil测试代码:
None.gif     public  class TestReflectionUtil
ExpandedBlockStart.gif     {
InBlock.gif        public static string Execute()
ExpandedSubBlockStart.gif        {
InBlock.gif            string result = string.Empty;
InBlock.gif            result += "使用ReflectionUtil反射操作辅助类:" + "\r\n";
InBlock.gif
InBlock.gif            try
ExpandedSubBlockStart.gif            {
InBlock.gif                Person person = new Person();
InBlock.gif                person.Name = "wuhuacong";
InBlock.gif                person.Age = 20;
InBlock.gif                result += DecriptPerson(person);
InBlock.gif
InBlock.gif                person.Name = "Wade Wu";
InBlock.gif                person.Age = 99;
InBlock.gif                result += DecriptPerson(person);
ExpandedSubBlockEnd.gif            }
InBlock.gif            catch (Exception ex)
ExpandedSubBlockStart.gif            {
InBlock.gif                result += string.Format("发生错误:{0}!\r\n \r\n", ex.Message);
ExpandedSubBlockEnd.gif            }
InBlock.gif            return result;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        public static string DecriptPerson(Person person)
ExpandedSubBlockStart.gif        {
InBlock.gif            string result = string.Empty;
InBlock.gif
InBlock.gif            result += "name:" + ReflectionUtil.GetField(person, "name") + "\r\n";
InBlock.gif            result += "age" + ReflectionUtil.GetField(person, "age") + "\r\n";
InBlock.gif
InBlock.gif            result += "Name:" + ReflectionUtil.GetProperty(person, "Name") + "\r\n";
InBlock.gif            result += "Age:" + ReflectionUtil.GetProperty(person, "Age") + "\r\n";
InBlock.gif
ExpandedSubBlockStart.gif            result += "Say:" + ReflectionUtil.InvokeMethod(person, "Say", new object[] {}) + "\r\n";
InBlock.gif
InBlock.gif            result += "操作完成!\r\n \r\n";
InBlock.gif
InBlock.gif            return result;
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
3. 注册表访问辅助类RegistryHelper
ExpandedBlockStart.gif     /// <summary>
InBlock.gif    
/// 注册表访问辅助类
ExpandedBlockEnd.gif    
/// </summary>
None.gif     public  sealed  class RegistryHelper
ExpandedBlockStart.gif     {
InBlock.gif        private string softwareKey = string.Empty;
InBlock.gif        private RegistryKey rootRegistry = Registry.CurrentUser;
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 使用注册表键构造,默认从Registry.CurrentUser开始。
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="softwareKey">注册表键,格式如"SOFTWARE\\Huaweisoft\\EDNMS"的字符串</param>
InBlock.gif        public RegistryHelper(string softwareKey) : this(softwareKey, Registry.CurrentUser)
ExpandedSubBlockStart.gif        {
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 指定注册表键及开始的根节点查询
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="softwareKey">注册表键</param>
ExpandedSubBlockEnd.gif        
/// <param name="rootRegistry">开始的根节点(Registry.CurrentUser或者Registry.LocalMachine等)</param>
InBlock.gif        public RegistryHelper(string softwareKey, RegistryKey rootRegistry)
ExpandedSubBlockStart.gif        {
InBlock.gif            this.softwareKey = softwareKey;
InBlock.gif            this.rootRegistry = rootRegistry;
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 根据注册表的键获取键值。
InBlock.gif        
/// 如果注册表的键不存在,返回空字符串。
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="key">注册表的键</param>
ExpandedSubBlockEnd.gif        
/// <returns>键值</returns>
InBlock.gif        public string GetValue(string key)
ExpandedSubBlockStart.gif        {
InBlock.gif            const string parameter = "key";
InBlock.gif            if (null == key)
ExpandedSubBlockStart.gif            {
InBlock.gif                throw new ArgumentNullException(parameter);
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            string result = string.Empty;
InBlock.gif            try
ExpandedSubBlockStart.gif            {
InBlock.gif                RegistryKey registryKey = rootRegistry.OpenSubKey(softwareKey);
InBlock.gif                result = registryKey.GetValue(key).ToString();
ExpandedSubBlockEnd.gif            }
InBlock.gif            catch
ExpandedSubBlockStart.gif            {
InBlock.gif                ;
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            return result;
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 保存注册表的键值
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="key">注册表的键</param>
InBlock.gif        
/// <param name="value">键值</param>
ExpandedSubBlockEnd.gif        
/// <returns>成功返回true,否则返回false.</returns>
InBlock.gif        public bool SaveValue(string key, string value)
ExpandedSubBlockStart.gif        {
InBlock.gif            const string parameter1 = "key";
InBlock.gif            const string parameter2 = "value";
InBlock.gif            if (null == key)
ExpandedSubBlockStart.gif            {
InBlock.gif                throw new ArgumentNullException(parameter1);
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            if (null == value)
ExpandedSubBlockStart.gif            {
InBlock.gif                throw new ArgumentNullException(parameter2);
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            RegistryKey registryKey = rootRegistry.OpenSubKey(softwareKey, true);
InBlock.gif
InBlock.gif            if (null == registryKey)
ExpandedSubBlockStart.gif            {
InBlock.gif                registryKey = rootRegistry.CreateSubKey(softwareKey);
ExpandedSubBlockEnd.gif            }
InBlock.gif            registryKey.SetValue(key, value);
InBlock.gif
InBlock.gif            return true;
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
注册表访问辅助类RegistryHelper测试代码:
None.gif     public  class TestRegistryHelper
ExpandedBlockStart.gif     {
InBlock.gif        public static string Execute()
ExpandedSubBlockStart.gif        {
InBlock.gif            string result = string.Empty;
InBlock.gif            result += "使用RegistryHelper注册表访问辅助类:" + "\r\n";
InBlock.gif
InBlock.gif            RegistryHelper registry = new RegistryHelper("SoftWare\\HuaweiSoft\\EDNMS");
InBlock.gif            bool sucess = registry.SaveValue("Test", DateTime.Now.ToString("hh:mm:ss"));
InBlock.gif            if (sucess)
ExpandedSubBlockStart.gif            {
InBlock.gif                result += registry.GetValue("Test");
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            return result;
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
4. 压缩/解压缩辅助类ZipUtil
ExpandedBlockStart.gif     /// <summary>
InBlock.gif    
/// 压缩/解压缩辅助类
ExpandedBlockEnd.gif    
/// </summary>
None.gif     public  sealed  class ZipUtil
ExpandedBlockStart.gif     {
InBlock.gif        private ZipUtil()
ExpandedSubBlockStart.gif        {
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 压缩文件操作
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="fileToZip">待压缩文件名</param>
InBlock.gif        
/// <param name="zipedFile">压缩后的文件名</param>
InBlock.gif        
/// <param name="compressionLevel">0~9,表示压缩的程度,9表示最高压缩</param>
ExpandedSubBlockEnd.gif        
/// <param name="blockSize">缓冲块大小</param>
InBlock.gif        public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
ExpandedSubBlockStart.gif        {
InBlock.gif            if (! File.Exists(fileToZip))
ExpandedSubBlockStart.gif            {
InBlock.gif                throw new FileNotFoundException("文件 " + fileToZip + " 没有找到,取消压缩。");
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            using (FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
ExpandedSubBlockStart.gif            {
InBlock.gif                FileStream fileStream = File.Create(zipedFile);
InBlock.gif                using (ZipOutputStream zipStream = new ZipOutputStream(fileStream))
ExpandedSubBlockStart.gif                {
InBlock.gif                    ZipEntry zipEntry = new ZipEntry(fileToZip);
InBlock.gif                    zipStream.PutNextEntry(zipEntry);
InBlock.gif                    zipStream.SetLevel(compressionLevel);
InBlock.gif
InBlock.gif                    byte[] buffer = new byte[blockSize];
InBlock.gif                    Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
InBlock.gif                    zipStream.Write(buffer, 0, size);
InBlock.gif
InBlock.gif                    try
ExpandedSubBlockStart.gif                    {
InBlock.gif                        while (size < streamToZip.Length)
ExpandedSubBlockStart.gif                        {
InBlock.gif                            int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
InBlock.gif                            zipStream.Write(buffer, 0, sizeRead);
InBlock.gif                            size += sizeRead;
ExpandedSubBlockEnd.gif                        }
ExpandedSubBlockEnd.gif                    }
InBlock.gif                    catch (Exception ex)
ExpandedSubBlockStart.gif                    {
InBlock.gif                        throw ex;
ExpandedSubBlockEnd.gif                    }
InBlock.gif                    zipStream.Finish();
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        
/// 打开sourceZipPath的压缩文件,解压到destPath目录中
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="sourceZipPath">待解压的文件路径</param>
ExpandedSubBlockEnd.gif        
/// <param name="destPath">解压后的文件路径</param>
InBlock.gif        public static void UnZipFile(string sourceZipPath, string destPath)
ExpandedSubBlockStart.gif        {
InBlock.gif            if (!destPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
ExpandedSubBlockStart.gif            {
InBlock.gif                destPath = destPath + Path.DirectorySeparatorChar;
ExpandedSubBlockEnd.gif            }
InBlock.gif
InBlock.gif            using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(sourceZipPath)))
ExpandedSubBlockStart.gif            {
InBlock.gif                ZipEntry theEntry;
InBlock.gif                while ((theEntry = zipInputStream.GetNextEntry()) != null)
ExpandedSubBlockStart.gif                {
InBlock.gif                    string fileName = destPath + Path.GetDirectoryName(theEntry.Name) +
InBlock.gif                        Path.DirectorySeparatorChar + Path.GetFileName(theEntry.Name);
InBlock.gif
InBlock.gif                    //create directory for file (if necessary)
InBlock.gif
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
InBlock.gif
InBlock.gif                    if (!theEntry.IsDirectory)
ExpandedSubBlockStart.gif                    {
InBlock.gif                        using (FileStream streamWriter = File.Create(fileName))
ExpandedSubBlockStart.gif                        {
InBlock.gif                            int size = 2048;
InBlock.gif                            byte[] data = new byte[size];
InBlock.gif                            try
ExpandedSubBlockStart.gif                            {
InBlock.gif                                while (true)
ExpandedSubBlockStart.gif                                {
InBlock.gif                                    size = zipInputStream.Read(data, 0, data.Length);
InBlock.gif                                    if (size > 0)
ExpandedSubBlockStart.gif                                    {
InBlock.gif                                        streamWriter.Write(data, 0, size);
ExpandedSubBlockEnd.gif                                    }
InBlock.gif                                    else
ExpandedSubBlockStart.gif                                    {
InBlock.gif                                        break;
ExpandedSubBlockEnd.gif                                    }
ExpandedSubBlockEnd.gif                                }
ExpandedSubBlockEnd.gif                            }
InBlock.gif                            catch
ExpandedSubBlockStart.gif                            {
ExpandedSubBlockEnd.gif                            }
ExpandedSubBlockEnd.gif                        }
ExpandedSubBlockEnd.gif                    }
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
压缩/解压缩辅助类ZipUtil测试代码:
None.gif     public  class TestZipUtil
ExpandedBlockStart.gif     {
InBlock.gif        public static string Execute()
ExpandedSubBlockStart.gif        {
InBlock.gif            string result = string.Empty;
InBlock.gif            result += "使用ZipUtil压缩/解压缩辅助类:" + "\r\n";
InBlock.gif
InBlock.gif            try
ExpandedSubBlockStart.gif            {
InBlock.gif                ZipUtil.ZipFile("Web.Config", "Test.Zip", 6, 512);
InBlock.gif                ZipUtil.UnZipFile("Test.Zip", "Test");
InBlock.gif
InBlock.gif                result += "操作完成!\r\n \r\n";
ExpandedSubBlockEnd.gif            }
InBlock.gif            catch (Exception ex)
ExpandedSubBlockStart.gif            {
InBlock.gif                result += string.Format("发生错误:{0}!\r\n \r\n", ex.Message);
ExpandedSubBlockEnd.gif            }
InBlock.gif            return result;
ExpandedSubBlockEnd.gif        }
ExpandedBlockEnd.gif    }
本文转自博客园伍华聪的博客,原文链接: .NET开发不可不知、不可不用的辅助类(一),如需转载请自行联系原博主。


相关文章:

  • python 单元测试 unittest
  • 基础的POJ学习
  • 冲刺NO.8
  • ajax同步和异步
  • jBPM开发入门指南(3)
  • Git与GitHub学习笔记(七)Windows 配置Github ssh key
  • java序列化方式性能比较
  • 【元气云妹】短信服务
  • sNote(自己的学习笔记)想法
  • Tomcat配置-学习笔记1---核心配合文件server.xml整体结构
  • 熔断器 Hystrix 源码解析 —— 命令执行(二)之执行隔离策略
  • Java Applet 基础
  • 使用svnadmin对VisualSVN进行项目迁移
  • 洛谷——P1123 取数游戏
  • SpringMVC-@CookieValue
  • ----------
  • 【译】理解JavaScript:new 关键字
  • DataBase in Android
  • git 常用命令
  • Java IO学习笔记一
  • Java新版本的开发已正式进入轨道,版本号18.3
  • JS题目及答案整理
  • miniui datagrid 的客户端分页解决方案 - CS结合
  • MySQL主从复制读写分离及奇怪的问题
  • node.js
  • Otto开发初探——微服务依赖管理新利器
  • PAT A1017 优先队列
  • Vue2.x学习三:事件处理生命周期钩子
  • Windows Containers 大冒险: 容器网络
  • 百度地图API标注+时间轴组件
  • 从 Android Sample ApiDemos 中学习 android.animation API 的用法
  • 番外篇1:在Windows环境下安装JDK
  • 开源SQL-on-Hadoop系统一览
  • 力扣(LeetCode)56
  • 入职第二天:使用koa搭建node server是种怎样的体验
  • 少走弯路,给Java 1~5 年程序员的建议
  • 使用权重正则化较少模型过拟合
  • 腾讯优测优分享 | 你是否体验过Android手机插入耳机后仍外放的尴尬?
  • 微服务核心架构梳理
  • 一些基于React、Vue、Node.js、MongoDB技术栈的实践项目
  • 翻译 | The Principles of OOD 面向对象设计原则
  • 扩展资源服务器解决oauth2 性能瓶颈
  • 小白应该如何快速入门阿里云服务器,新手使用ECS的方法 ...
  • #pragma data_seg 共享数据区(转)
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • (31)对象的克隆
  • (6)【Python/机器学习/深度学习】Machine-Learning模型与算法应用—使用Adaboost建模及工作环境下的数据分析整理
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (附源码)spring boot校园健康监测管理系统 毕业设计 151047
  • (附源码)springboot 个人网页的网站 毕业设计031623
  • (力扣记录)235. 二叉搜索树的最近公共祖先
  • (原創) 未来三学期想要修的课 (日記)
  • (转)Sublime Text3配置Lua运行环境
  • (轉貼)《OOD启思录》:61条面向对象设计的经验原则 (OO)
  • ... 是什么 ?... 有什么用处?