您现在的位置是:首页 >其他 >c#INI配置文件的读取写入网站首页其他

c#INI配置文件的读取写入

日月清心 2025-03-26 12:01:02
简介c#INI配置文件的读取写入

INI配置文件的读取写入

在上位机程序开发或者其他软件开发当中,通常用户需要对部分功能设置做保存。

例如打印报表功能,用户在勾选需要打印报表选框之后,如果退出重启软件而需要重新勾选的话就不太方便。所以需要对当前是否勾选做保存,然而在软件关闭重启的过程中,所有的变量都会被初始化,这个时候就需要把功能是否勾选这个变量写在程序外部,这里演示用INI配置文件来完成这个操作。

  • IniGet.cs文件如下
  • 这个文件作用在于引用配置文件的库,同时定义配置文件的读取写入格式,只需要添加进项目里就可以使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace getini
{
    public class IniGet
    {
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);


        private string ReadString(string section, string key, string def, string filePath)
        {
            StringBuilder temp = new StringBuilder(1024);

            try
            {
                GetPrivateProfileString(section, key, def, temp, 1024, filePath);
            }
            catch
            { }
            return temp.ToString();
        }

        public void INIWrite(string section, string key, string value, string path)
        {
            //section=配置节点名称,key=键名,value=返回键值,path=路径
            WritePrivateProfileString(section, key, value, path);
        }



        public Dictionary<string, string> ReadIniAllKeys(string section, string filePath)
        {
            UInt32 MAX_BUFFER = 32767;

            Dictionary<string, string> dictionary = new Dictionary<string, string>();

            string[] items = new string[0];

            IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));

            UInt32 bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, filePath);

            if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
            {
                string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);

                items = returnedString.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries);
            }

            Marshal.FreeCoTaskMem(pReturnedString);

            foreach (string item in items)
            {
                string[] ary = item.Split('=');
                dictionary.Add(ary[0], ary[1]);

            }

            return dictionary;
        }


        public  string ReadIniKeys(string section, string keys, string filePath)
        {
            return ReadString(section, keys, "", filePath);
        }
    }
}

使用步骤

  1. 将上述.cs文件引用进项目

  2. 在当前项目debug文件夹下创建一个config.ini文件,文件内容如下(具体ini文件如何创建自行搜索,这里不作演示)在这里插入图片描述

  3. 实例化.cs文件并且做读取和写入,代码如下:

//实例化
IniGet getIni = new IniGet();

//INIPath 为 config.ini 配置文件的路径,通常写为(即项目执行文件同目录下的 config.ini 文件):
string INIPath = Convert.ToString(System.AppDomain.CurrentDomain.BaseDirectory) + "config.ini";

//写入当前文件夹下 config.ini 配置文件下 Detection 项的 row 子项
getIni.INIWrite("Detection", "row", "10" , INIPath);//此时配置文件里的值赋为10

//读取当前文件夹下 config.ini 配置文件下 Detection 项的 row 子项
Dictionary<string, string> Detection = getIni.ReadIniAllKeys("Detection", INIPath);
string row = Detection["row"];//此时row变量即配置文件里的值


通过INI配置文件的读取,可以实现代码外的变量保存或是值的保存,对代码的可读性和维护性有很大的提升。

最重要的是,简化了客户大爹的操作,一切都是为了客户!

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。