C# 实现对ini配置文件的读写操作

背景:

我们在做项目的过程中经常都需要对配置文件进行操作 .config   .ini 等配置文件,今天我们先来学习一下对.ini配置文件的操作。

主要使用kernel32.dll动态链接库的两个方法:

GetPrivateProfileString()和WritePrivateProfileString();

首先我们先分别对两个方法的参数进行一个简单的了解

int GetPrivateProfileString(
  String section,        // ini文件中的一个字段名[节名]可以有很多个节名
  String KeyName,        // section 下的一个键名,也就是里面具体的变量名
  String str,        // 如果pipvalue为空,则把个变量赋给pipvalue
  LPTSTR pipvalue,  // 用于接收ini文件中键值(数据)的接收缓冲区
  int size,          // pipvalue的缓冲区大小
  String path        // ini文件的路径
);
long WritePrivateProfileString(
  String  section,  // ini文件中的一个字段名[节名]可以有很多个节名
  String  key,  // section下的一个键名,也就是里面具体的变量名
  String  values,   // 键值,也就是数据
  String  path // ini文件的路径
);

现在开始写一个demo对下面的配置文件进行操作

首先我们需要先创建一个操作ini配置文件的类

class Ini_Operate
    {       
        [DllImport("kernel32")]

        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]

        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

        private string Path = null;
        public Ini_Operate(string path)
        {
            this.Path = path;
        }

        //写
        public void Write(string section, string key, string value)
        {           

            try
            {
                WritePrivateProfileString(section, key, value, Path);
            }
            catch
            {
                throw (new ApplicationException("写Ini文件出错!"));
            }

        }

        //读
        public string ReadValue(string section, string key)
        {
            try
            {              

                System.Text.StringBuilder builder= new System.Text.StringBuilder(255);                

                GetPrivateProfileString(section, key, "", builder, 255, Path);

                return builder.ToString();
            }
            catch (Exception ex)
            {
                throw (ex);
            }

        }

    }

测试类:

先测试读取ini文件

 Ini_Operate ini1 = null;
 ini1 = new Ini_Operate( @"E:\\config.ini");
 string Server = ini1.ReadValue("MySQL", "Server");
 Console.WriteLine(Server);

结果:

再测试写ini配置文件

Ini_Operate ini1 = null;
ini1 = new Ini_Operate( @"E:\\config.ini");
ini1.Write("MySQL", "ip" ,"127.0.0.2");

结果:

如果有不清楚的欢迎评论留言

发布了20 篇原创文章 · 获赞 25 · 访问量 2170

猜你喜欢

转载自blog.csdn.net/qq_38992372/article/details/102972381