配置处理工具类

本文介绍了如何通过C#调用WindowsAPI函数实现配置文件的读取、写入、删除键值对以及检查键是否存在。作者提供了完整代码示例,包括MyConfigHandle类的方法实现及其在测试中的应用。

一 调用wingdows API

  #region 使用WindowsAPI函数实现读写配置文件-固定写法
  [DllImport("kernel32", CharSet = CharSet.Unicode)]
  static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);
  [DllImport("kernel32", CharSet = CharSet.Unicode)]
  static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

  #endregion

 

 

二 实现配置文件的增删改查


        //读取
        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        //写入
        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        //删除键
        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        //删除节点
        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        //判断键是否存在
        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }

 

三 完整代码

using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StandDevelopTemple.Tools
{
    //配置处理类
    internal class MyConfigHandle
    {
      

        #region 使用WindowsAPI函数实现读写配置文件-固定写法
        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath);
        [DllImport("kernel32", CharSet = CharSet.Unicode)]
        static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

        #endregion
        string EXE = Assembly.GetExecutingAssembly().GetName().Name; //获取当前项目名称
        string Path; //存储路径


        //IniPath若不设置路径,则默认为当前可执行文件所在路径
        public MyConfigHandle(string IniPath = null)
        {
            //给IniPath赋默认值值
            if (IniPath == null)  IniPath = System.Environment.CurrentDirectory;

            try
            {
                //输出当前可执行文件的完整路径
                Path = new FileInfo(IniPath ?? EXE + ".ini").FullName+"\\"+EXE+".config";
                //文件不存在则创建
                if (!File.Exists(Path))
                {
                    FileStream fs = File.Create(Path);//创建文件
                    fs.Close();
                    
                }


            }
            catch (Exception e)
            {
                //输入路径为空或不存在异常
                logger.Error( MethodInfo.GetCurrentMethod().Name+"=>"+e);
                MessageBox.Show("配置文件路径为空或不存在异常");
            }
           
        }


        //读取
        public string Read(string Key, string Section = null)
        {
            var RetVal = new StringBuilder(255);
            GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path);
            return RetVal.ToString();
        }

        //写入
        public void Write(string Key, string Value, string Section = null)
        {
            WritePrivateProfileString(Section ?? EXE, Key, Value, Path);
        }

        //删除键
        public void DeleteKey(string Key, string Section = null)
        {
            Write(Key, null, Section ?? EXE);
        }

        //删除节点
        public void DeleteSection(string Section = null)
        {
            Write(null, null, Section ?? EXE);
        }

        //判断键是否存在
        public bool KeyExists(string Key, string Section = null)
        {
            return Read(Key, Section).Length > 0;
        }


        //测试方法
        public void MyConfigHandleTest(int model)
        {
            switch (model)
            {
                //写入
                case 1:
                    Write("name", "黎明");
                    Write("age", "33");
                    //写入时指定配置
                    Write("hubby", "篮球", "hubby");

                    logger.Info("name");
                    logger.Info("age");
                    logger.Info("hubby");
                    break;

                    //读取
                    case 2:
                    //读取到日志中
                    logger.Info(Read("name"));
                    logger.Info(Read("age"));
                    break; 
                
                //检索键是否存在
                case 3:
                    if (KeyExists("name"))
                    {
                        logger.Info("name" + "====存在");
                    }
                    break;

                //删除配置KEY
                case 4:
                    if (KeyExists("name"))
                    {
                        DeleteKey("name");  
                        logger.Info("name" + "====删除成功");
                    }
                    break;

                //删除配置项
                case 5:
                    DeleteSection("hubby");   
                        logger.Info("hubby" + "====删除成功");
                    
                    break;
            }
           

            
        }
    }
}

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code_shenbing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值