C# 操作ini文件

INI文件其实是一种具有特定结构的文本文件,它的构成分为三部分,结构如下:

[Section1]
key 1 = value2
key 1 = value2
……
[Section2]
key 1 = value1
key 2 = value2
……

文件由若干个段落(section)组成,每个段落又分成若干个键(key)和值(value)。Windows系统自带的Win32的API函数GetPrivateProfileString()和WritePrivateProfileString()分别实现了对INI文件的读写操作,他们位于kernel32.dll下。

但是令人遗憾的是C#所使用的.NET框架下的公共类库并没有提供直接操作INI文件的类,所以唯一比较理想的方法就是调用API函数。

然后,.Net框架下的类库是基于托管代码的,而API函数是基于非托管代码的,(在运行库的控制下执行的代码称作托管代码。相反,在运行库之外运行的代码称作非托管代码。)如何实现托管代码与非托管代码之间的操作呢?.Net框架的System.Runtime.InteropServices命名空间下提供各种各样支持COM interop及平台调用服务的成员,其中最重要的属性之一DllImportAttribute可以用来定义用于访问非托管API的平台调用方法,它提供了对从非托管DLL导出的函数进行调用所必需的信息。下面就来看一下如何实现C#与API函数的互操作。

using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace MyLibs.Files { public class IniFile { public string IniPath { get; set; } 声明读写INI文件的API函数 [DllImport("kernel32")] private static extern long 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); [DllImport("kernel32", EntryPoint = "WritePrivateProfileSection")] private static extern void WriteSection(string Section, string Key, string FilePath); /// <summary> /// 写ini文件 /// </summary> /// <param name="Section">Section</param> /// <param name="Key">Key</param> /// <param name="Value">Value</param> public void IniWriteValue(string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, this.IniPath); } /// <summary> /// 读取ini节点的键值 /// </summary> /// <param name="Section">Section</param> /// <param name="Key">Key</param> /// <returns>string</returns> public string IniReadValue(string Section, string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.IniPath); return temp.ToString(); } /// <summary> /// 添加一个节点 /// </summary> /// <param name="Section">Section</param> /// <param name="Text">Text</param> public void WriteSection(string Section, string Text) { WriteSection(Section, Text, this.IniPath); } /// <summary> /// 只添加一个节点,无任何键值 /// </summary> /// <param name="Section">要添加的节点</param> public void WriteSection(string Section) { WriteSection(Section, "", this.IniPath); } /// <summary> /// 删除该节 /// </summary> /// <param name="Section"></param> public void DeleteSection(string Section) { WritePrivateProfileString(Section, null, "value", this.IniPath); } /// <summary> /// 删除节点中一个键 /// </summary> /// <param name="Section"></param> public void DeleteKey(string Section, string Key) { WritePrivateProfileString(Section, Key, null, this.IniPath); } } }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值