当前位置: 首页 > 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
  • 30秒的PHP代码片段(1)数组 - Array
  • CentOS 7 修改主机名
  • CSS 专业技巧
  • java8 Stream Pipelines 浅析
  • JavaScript DOM 10 - 滚动
  • JavaScript异步流程控制的前世今生
  • UEditor初始化失败(实例已存在,但视图未渲染出来,单页化)
  • vue中实现单选
  • Web设计流程优化:网页效果图设计新思路
  • 对话 CTO〡听神策数据 CTO 曹犟描绘数据分析行业的无限可能
  • 工程优化暨babel升级小记
  • 基于axios的vue插件,让http请求更简单
  • 项目实战-Api的解决方案
  • 小程序button引导用户授权
  • 用Canvas画一棵二叉树
  • ​你们这样子,耽误我的工作进度怎么办?
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • #{} 和 ${}区别
  • #162 (Div. 2)
  • (12)Hive调优——count distinct去重优化
  • (C语言)共用体union的用法举例
  • (Forward) Music Player: From UI Proposal to Code
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (未解决)jmeter报错之“请在微信客户端打开链接”
  • (一)Dubbo快速入门、介绍、使用
  • (一)插入排序
  • (原創) 如何刪除Windows Live Writer留在本機的文章? (Web) (Windows Live Writer)
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)C#调用WebService 基础
  • (转载)微软数据挖掘算法:Microsoft 时序算法(5)
  • .bat批处理(二):%0 %1——给批处理脚本传递参数
  • .gitattributes 文件
  • .NET “底层”异步编程模式——异步编程模型(Asynchronous Programming Model,APM)...
  • .net core 控制台应用程序读取配置文件app.config
  • ??myeclipse+tomcat
  • [BUUCTF 2018]Online Tool(特详解)
  • [C#小技巧]如何捕捉上升沿和下降沿
  • [FT]chatglm2微调
  • [HackMyVM]靶场 VivifyTech
  • [HarekazeCTF2019]encode_and_encode 不会编程的崽