.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开发不可不知、不可不用的辅助类(一),如需转载请自行联系原博主。


目录
相关文章
|
22天前
|
开发框架 算法 Java
.NET 开发:实现高效能的秘诀
【7月更文挑战第4天】探索.NET高效开发涉及理解运行时(如GC、JIT)、代码与算法优化及工具利用。关键点包括适应性垃圾回收、异步编程、明智的并发控制;编写高效代码(避免对象创建,选对数据结构和算法);使用性能分析工具,善用高性能框架如ASP.NET Core,并借助云服务和CI/CD流程持续优化。性能优化是持续学习与实践的过程。
27 1
|
3天前
|
开发框架 搜索推荐 前端开发
【.NET全栈】ASP.NET开发Web应用——Web部件技术
【.NET全栈】ASP.NET开发Web应用——Web部件技术
|
1月前
|
开发框架 前端开发 .NET
LIMS(实验室)信息管理系统源码、有哪些应用领域?采用C# ASP.NET dotnet 3.5 开发的一套实验室信息系统源码
集成于VS 2019,EXT.NET前端和ASP.NET后端,搭配MSSQL 2018数据库。系统覆盖样品管理、数据分析、报表和项目管理等实验室全流程。应用广泛,包括生产质检(如石化、制药)、环保监测、试验研究等领域。随着技术发展,现代LIMS还融合了临床、电子实验室笔记本和SaaS等功能,以满足复杂多样的实验室管理需求。
43 3
LIMS(实验室)信息管理系统源码、有哪些应用领域?采用C# ASP.NET dotnet 3.5 开发的一套实验室信息系统源码
|
22天前
|
人工智能 前端开发 Devops
NET技术在现代开发中的影响力日益增强,本文聚焦其核心价值,如多语言支持、强大的Visual Studio工具、丰富的类库和跨平台能力。
【7月更文挑战第4天】**.NET技术在现代开发中的影响力日益增强,本文聚焦其核心价值,如多语言支持、强大的Visual Studio工具、丰富的类库和跨平台能力。实际应用涵盖企业系统、Web、移动和游戏开发,以及云服务。面对性能挑战、容器化、AI集成及跨平台竞争,.NET持续创新,开发者应关注技术趋势,提升技能,并参与社区,共同推进技术发展。**
18 1
|
22天前
|
机器学习/深度学习 人工智能 开发者
.NET 技术:为开发带来新机遇
【7月更文挑战第4天】**.NET技术开启软件开发新篇章,通过跨平台革命(.NET Core, Xamarin, .NET MAUI)、云服务与微服务(Azure, DevOps, Docker)及AI集成(ML.NET, 认知服务, TensorFlow)为开发者创造新机遇。开源社区的繁荣与性能提升使.NET更具竞争力,推动智能应用的创新与发展。开发者需紧跟潮流,利用这些工具和框架构建高效、创新的解决方案。**
19 1
|
1月前
|
存储 Go C#
【.NET Core】深入理解IO之File类
【.NET Core】深入理解IO之File类
41 6
|
1月前
|
开发框架 JavaScript 前端开发
分享7个.NET开源、功能强大的快速开发框架
分享7个.NET开源、功能强大的快速开发框架
117 1
|
2月前
|
开发框架 .NET C#
使用C#进行.NET框架开发:深入探索与实战
【5月更文挑战第28天】本文探讨了C#在.NET框架中的应用,展示了其作为强大编程语言的特性,如类型安全、面向对象编程。C#与.NET框架的结合,提供了一站式的开发环境,支持跨平台应用。文中介绍了C#的基础知识,如数据类型、控制结构和面向对象编程,以及.NET的关键技术,包括LINQ、ASP.NET和WPF。通过一个实战案例,展示了如何使用C#和ASP.NET开发Web应用,包括项目创建、数据库设计、模型和控制器编写,以及视图和路由配置。本文旨在揭示C#在.NET开发中的深度和广度,激发开发者探索更多可能性。
|
1月前
|
存储 开发框架 缓存
【.NET Core】你真的了解HttpRuntime类吗
【.NET Core】你真的了解HttpRuntime类吗
20 0
|
2月前
|
消息中间件
.NET 中 Channel 类简单使用
`System.Threading.Channels` 提供异步生产者-消费者数据结构,用于.NET Standard上的跨平台同步。频道实现生产者/消费者模型,允许在任务间异步传递数据。简单示例展示如何创建无界和有界频道,以及多生产者和消费者共享频道的场景。频道常用于内存中的消息队列,通过控制生产者和消费者的速率来调整系统流量。