一个完整的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
知乎: @张赐荣
赐荣博客: www.prc.cx
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!