张赐荣——一位视障程序员。
赐荣小站: www.prc.cx

張賜榮

张赐荣的技术博客

博客园 首页 新随笔 联系 订阅 管理
  92 随笔 :: 27 文章 :: 2 评论 :: 77074 阅读

一个完整的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

posted on   张赐荣  阅读(913)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

感谢访问张赐荣的技术分享博客!
博客地址:https://cnblogs.com/netlog/
知乎主页:https://www.zhihu.com/people/tzujung-chang
个人网站:https://prc.cx/

点击右上角即可分享
微信分享提示