.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;
        }

    }
本文转自博客园伍华聪的博客,原文链接: .NET开发不可不知、不可不用的辅助类(一),如需转载请自行联系原博主。


目录
相关文章
|
10月前
|
人工智能 芯片
D1net阅闻|OpenAI员工疯狂暗示,内部已成功开发ASI?被曝训出GPT-5但雪藏
D1net阅闻|OpenAI员工疯狂暗示,内部已成功开发ASI?被曝训出GPT-5但雪藏
|
8月前
|
SQL 小程序 API
如何运用C#.NET技术快速开发一套掌上医院系统?
本方案基于C#.NET技术快速构建掌上医院系统,结合模块化开发理念与医院信息化需求。核心功能涵盖用户端的预约挂号、在线问诊、报告查询等,以及管理端的排班管理和数据统计。采用.NET Core Web API与uni-app实现前后端分离,支持跨平台小程序开发。数据库选用SQL Server 2012,并通过读写分离与索引优化提升性能。部署方案包括Windows Server与负载均衡设计,确保高可用性。同时针对API差异、数据库老化及高并发等问题制定应对措施,保障系统稳定运行。推荐使用Postman、Redgate等工具辅助开发,提升效率与质量。
300 0
|
12月前
|
JSON 安全 API
.net 自定义日志类
在.NET中,创建自定义日志类有助于更好地管理日志信息。示例展示了如何创建、配置和使用日志记录功能,包括写入日志文件、设置日志级别、格式化消息等。注意事项涵盖时间戳、日志级别、JSON序列化、线程安全、日志格式、文件处理及示例使用。请根据需求调整代码。
186 13
|
12月前
|
缓存 算法 安全
精选10款C#/.NET开发必备类库(含使用教程),工作效率提升利器!
精选10款C#/.NET开发必备类库(含使用教程),工作效率提升利器!
374 12
|
12月前
|
Linux API C#
基于 .NET 开发的多功能流媒体管理控制平台
基于 .NET 开发的多功能流媒体管理控制平台
199 9
|
12月前
|
Web App开发 前端开发 调度
一款基于 .NET + Blazor 开发的智能访客管理系统
一款基于 .NET + Blazor 开发的智能访客管理系统
172 8
|
12月前
|
前端开发 JavaScript C#
基于.NET8+Vue3开发的权限管理&个人博客系统
基于.NET8+Vue3开发的权限管理&个人博客系统
180 7
|
12月前
|
网络协议 C#
基于.NET WinForm开发的一款硬件及协议通讯工具
基于.NET WinForm开发的一款硬件及协议通讯工具
136 7
|
12月前
|
监控 前端开发 API
一款基于 .NET MVC 框架开发、功能全面的MES系统
一款基于 .NET MVC 框架开发、功能全面的MES系统
343 5
|
12月前
|
JSON 数据格式
.net HTTP请求类封装
`HttpRequestHelper` 是一个用于简化 HTTP 请求的辅助类,支持发送 GET 和 POST 请求。它使用 `HttpClient` 发起请求,并通过 `Newtonsoft.Json` 处理 JSON 数据。示例展示了如何使用该类发送请求并处理响应。注意事项包括:简单的错误处理、需安装 `Newtonsoft.Json` 依赖,以及建议重用 `HttpClient` 实例以优化性能。
297 2

热门文章

最新文章