C#操作读写INI配置文件

2022/2/18 11:11:44

本文主要是介绍C#操作读写INI配置文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一个完整的INI文件格式由节(section)、键(key)、值(value)组成。
示例如:
[section]
key1=value1
key2=value2
; 备注:value的值不要太长,理论上最多不能超过65535个字节。

在Windows程序开发中经常会遇到读写INI配置文件的情况,以下C#类封装了对INI配置文件读写修改的操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace CRApp
{
    public class INIHelper
    {
        private string FilePath;
        public string Path
        {
            get { return this.FilePath; }
            set
            {
                if (value.Substring(0, 1) == "\\" || value.Substring(0, 1) == "/")
                {
                    this.FilePath = AppDomain.CurrentDomain + value;
                }
                else
                {
                    this.FilePath = value;
                }
            }
        }
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        public INIHelper(string _Path)
        {
            this.Path = _Path;
        }
        public void WriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.FilePath);
        }
        public string ReadValue(string Section, string Key)
        {
            try
            {
                StringBuilder temp = new StringBuilder();
                int i = GetPrivateProfileString(Section, Key, "", temp, -1, this.FilePath);
                return temp.ToString();
            }
            catch { return ""; }
        }
        public void RemoveKey(string Section, string Key)
        {
            WritePrivateProfileString(Section, Key, null, this.FilePath);
        }
        public bool RemoveSection(string Section)
        {
            return WritePrivateProfileString(Section, null, null, this.FilePath);
        }
        public bool Exists()
        {
            return System.IO.File.Exists(this.FilePath);
        }
    }
}

参考:
[1] WritePrivateProfileString 函数: https://baike.baidu.com/item/WritePrivateProfileString/9711454
[2] GetPrivateProfileString 函数: https://baike.baidu.com/item/GetPrivateProfileString/9642262



这篇关于C#操作读写INI配置文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程