C#读写ini文件

1.以前开发c#做一些数据持久化,基本上用的二进制序列化,XML文件,或者JOSN文件保存,这次用ini,记录一下

一、认识INI文件结构

INI文件格式由节、键、值组成。

[section]

参数

(键=值)

name=value

二、实操

在开发中,有时会遇到对INI文件的读写操作。

针对ini文件写了一个工具类。供大家参考。

引用库函数:

1 ///
2 /// 为INI文件中指定的节点取得字符串
3 ///
4 /// 欲在其中查找关键字的节点名称
5 /// 欲获取的项名
6 /// 指定的项没有找到时返回的默认值
7 /// 指定一个字串缓冲区,长度至少为nSize
8 /// 指定装载到lpReturnedString缓冲区的最大字符数量
9 /// INI文件完整路径
10 /// 复制到lpReturnedString缓冲区的字节数量,其中不包括那些NULL中止字符
11 [DllImport(“kernel32”)]
12 private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
13
14 ///
15 /// 修改INI文件中内容
16 ///
17 /// 欲在其中写入的节点名称
18 /// 欲设置的项名
19 /// 要写入的新字符串
20 /// INI文件完整路径
21 /// 非零表示成功,零表示失败
22 [DllImport(“kernel32”)]
23 private static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName);
复制代码
读写方法:

1 ///
2 /// 读取INI文件值
3 ///
4 /// 节点名
5 /// 键
6 /// 未取到值时返回的默认值
7 /// INI文件完整路径
8 /// 读取的值
9 public static string Read(string section, string key, string def, string filePath)
10 {
11 StringBuilder sb = new StringBuilder(1024);
12 GetPrivateProfileString(section, key, def, sb, 1024, filePath);
13 return sb.ToString();
14 }
15
16 ///
17 /// 写INI文件值
18 ///
19 /// 欲在其中写入的节点名称
20 /// 欲设置的项名
21 /// 要写入的新字符串
22 /// INI文件完整路径
23 /// 非零表示成功,零表示失败
24 public static int Write(string section, string key, string value, string filePath)
25 {
26 CheckPath(filePath);
27 return WritePrivateProfileString(section, key, value, filePath);
28 }
29
30 ///
31 /// 删除节
32 ///
33 /// 节点名
34 /// INI文件完整路径
35 /// 非零表示成功,零表示失败
36 public static int DeleteSection(string section, string filePath)
37 {
38 return Write(section, null, null, filePath);
39 }
40
41 ///
42 /// 删除键的值
43 ///
44 /// 节点名
45 /// 键名
46 /// INI文件完整路径
47 /// 非零表示成功,零表示失败
48 public static int DeleteKey(string section, string key, string filePath)
49 {
50 return Write(section, key, null, filePath);
51 }

在程序根目录创建一个INI文件:

string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, “sys.ini”);//在当前程序路径创建
File.Create(filePath);//创建INI文件
写入内容:

复制代码
//写入节点1
INIHelper.Write(“s1”, “1”, “a”, filePath);
INIHelper.Write(“s1”, “2”, “b”, filePath);
INIHelper.Write(“s1”, “3”, “c”, filePath);
//写入节点2
INIHelper.Write(“s2”, “4”, “d”, filePath);
INIHelper.Write(“s2”, “5”, “e”, filePath);
//改节点值(就是重写一遍)
INIHelper.Write(“s1”, “3”, “c3”, filePath);
复制代码
读取

//读取节点1中的key为1的值
string value = INIHelper.Read(“s1”, “1”, “789”, filePath);
删除节点/键

INIHelper.DeleteKey(“s1”, “2”, filePath);//删除节点s1中key为2的值
INIHelper.DeleteSection(“s1”, filePath);//删除节点s2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值