使用C#的INI文件处理类






4.79/5 (116投票s)
2002年3月15日

853288

19539
一个 C# 类,它暴露了 Kernal32.dll 中的 INI 文件处理函数。
引言
我创建了一个 C# 类 Ini
,它暴露了 KERNEL32.dll 中的 2 个函数。这些函数是: WritePrivateProfileString
和 GetPrivateProfileString
您需要的命名空间:System.Runtime.InteropServices
和 System.Text
类
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Ini
{
/// <summary>
/// Create a New INI file to store or load data
/// </summary>
public class IniFile
{
public string path;
[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);
/// <summary>
/// INIFile Constructor.
/// </summary>
/// <PARAM name="INIPath"></PARAM>
public IniFile(string INIPath)
{
path = INIPath;
}
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// Section name
/// <PARAM name="Key"></PARAM>
/// Key Name
/// <PARAM name="Value"></PARAM>
/// Value Name
public void IniWriteValue(string Section,string Key,string Value)
{
WritePrivateProfileString(Section,Key,Value,this.path);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <PARAM name="Path"></PARAM>
/// <returns></returns>
public string IniReadValue(string Section,string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section,Key,"",temp,
255, this.path);
return temp.ToString();
}
}
}
使用该类
使用 Ini
类的步骤
- 在您的项目命名空间定义中添加
using INI;
- 创建一个 INI 文件,如下所示
INIFile ini = new INIFile("C:\\test.ini");
- 使用
IniWriteValue
将新值写入特定节中的特定键,或使用IniReadValue
从特定节中的键读取值。
就这样。在 C# 中将 API 函数包含在您的类中非常容易。