[引用]关于C#操作INI文件的总结

本文介绍了如何使用C#调用Win32 API函数GetPrivateProfileString和WritePrivateProfileString来读写INI文件,并提供了一个IniFile类的具体实现,包括读取和写入INI文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 在写项目时遇到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函数的互操作。

读操作:


[DllImport("kernel32")]
None.gif
private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath); 
None.gifsection:要读取的段落名
None.gifkey: 要读取的键
None.gifdefVal: 读取异常的情况下的缺省值
None.gifretVal: key所对应的值,如果该key不存在则返回空值
None.gifsize: 值允许的大小
None.giffilePath: INI文件的完整路径和文件名

写操作:

None.gif[DllImport("kernel32")] 
None.gif
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 
None.gifsection: 要写入的段落名
None.gifkey: 要写入的键,如果该key存在则覆盖写入
None.gifval: key所对应的值
None.giffilePath: INI文件的完整路径和文件名

       这样,在就可以使用对他们的调用,用常规的方式定义一个名为IniFile类:
 1None.gif using System;
 2None.gif using System.Runtime.InteropServices; 
 3None.gif using System.Text; 
 4None.gif 
 5None.gif namespace IPVOD.Hotel.Remoting
 6ExpandedBlockStart.gifContractedBlock.gif dot.gif{
 7ExpandedSubBlockStart.gifContractedSubBlock.gif     /**//**//**//// <summary>
 8InBlock.gif    /// INI文件的操作类
 9ExpandedSubBlockEnd.gif    /// </summary>

10InBlock.gif    public class IniFile
11ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
12InBlock.gif        public string Path;
13InBlock.gif
14InBlock.gif        public IniFile(string path)
15ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
16InBlock.gif            this.Path = path;
17ExpandedSubBlockEnd.gif        }

18InBlock.gif       
19ContractedSubBlock.gifExpandedSubBlockStart.gif        声明读写INI文件的API函数声明读写INI文件的API函数#region 声明读写INI文件的API函数 
20InBlock.gif        [DllImport("kernel32")] 
21InBlock.gif        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 
22InBlock.gif
23InBlock.gif        [DllImport("kernel32")]
24InBlock.gif        private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath); 
25InBlock.gif
26InBlock.gif        [DllImport("kernel32")]
27InBlock.gif        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
28ExpandedSubBlockEnd.gif        #endregion

29InBlock.gif
30ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//**//**//// <summary>
31InBlock.gif        /// 写INI文件
32InBlock.gif        /// </summary>
33InBlock.gif        /// <param name="section">段落</param>
34InBlock.gif        /// <param name="key"></param>
35ExpandedSubBlockEnd.gif       /// <param name="iValue"></param>

36InBlock.gif        public void IniWriteValue(string section, string key, string iValue) 
37ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
38InBlock.gif            WritePrivateProfileString(section, key, iValue, this.Path);
39ExpandedSubBlockEnd.gif        }

40InBlock.gif
41ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//**//**//// <summary>
42InBlock.gif        /// 读取INI文件
43InBlock.gif        /// </summary>
44InBlock.gif        /// <param name="section">段落</param>
45InBlock.gif        /// <param name="key"></param>
46ExpandedSubBlockEnd.gif       /// <returns>返回的键值</returns>

47InBlock.gif        public string IniReadValue(string section, string key) 
48ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif
49InBlock.gif            StringBuilder temp = new StringBuilder(255); 
50InBlock.gif
51InBlock.gif            int i = GetPrivateProfileString(section, key, "", temp, 255this.Path); 
52InBlock.gif            return temp.ToString();
53ExpandedSubBlockEnd.gif        }

54InBlock.gif
55ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//**//**//// <summary>
56InBlock.gif        /// 读取INI文件
57InBlock.gif        /// </summary>
58InBlock.gif        /// <param name="Section">段,格式[]</param>
59InBlock.gif        /// <param name="Key"></param>
60ExpandedSubBlockEnd.gif        /// <returns>返回byte类型的section组或键值组</returns>

61InBlock.gif        public byte[] IniReadValues(string section, string key)
62ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
63InBlock.gif            byte[] temp = new byte[255];
64InBlock.gif
65InBlock.gif            int i = GetPrivateProfileString(section, key, "", temp, 255this.Path);
66InBlock.gif            return temp;
67ExpandedSubBlockEnd.gif       }

68ExpandedSubBlockEnd.gif    }

69ExpandedBlockEnd.gif}

70None.gif

DLL
导出的函数GetPrivateProfileString的重载

[DllImport("kernel32")] 
None.gif
private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
None.gifsection:要读取的段落名
None.gifkey: 要读取的键
None.gifdefVal: 读取异常的情况下的缺省值
None.gifretVal: 此参数类型不是string,而是Byte[]用于返回byte类型的section组或键值组。
None.gifsize: 值允许的大小
None.giffilePath: INI文件的完整路径和文件名

下面看一下具体实例化IniFile类的操作:

//pathini文件的物理路径

IniFile ini = new IniFile(path);

//读取ini文件的所有段落名

byte[] allSection = ini.IniReadValues(null, null);

 

通过如下方式转换byte[]类型为string[]数组类型

string[] sectionList;

ASCIIEncoding ascii = new ASCIIEncoding();

//获取自定义设置section中的所有keybyte[]类型

sectionByte = ini.IniReadValues("personal", null);

//编码所有keystring类型

sections = ascii.GetString(sectionByte);

//获取key的数组

sectionList = sections.Split(new char[1]{'\0'});

 

//读取ini文件personal段落的所有键名,返回byte[]类型

byte[] sectionByte = ini.IniReadValues("personal", null);

 

//读取ini文件evideo段落的MODEL键值

model = ini.IniReadValue("evideo", "MODEL");

 

//将值eth0写入ini文件evideo段落的DEVICE

ini.IniWriteValue("evideo", "DEVICE", "eth0");

即:

[evideo]

DEVICE = eth0

 

//删除ini文件下personal段落下的所有键

ini.IniWriteValue("personal", null, null);

 

//删除ini文件下所有段落

ini.IniWriteValue(null, null, null);


转载于:https://www.cnblogs.com/conquer/archive/2006/11/28/575684.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值