您的位置:首页 > 编程语言 > C#

C# 操作ini文件

2012-03-09 00:00 316 查看
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);
}

}
}


$(document).ready(function(){dp.SyntaxHighlighter.HighlightAll('code');});

原文链接:
http://blog.csdn.net/vince6799/article/details/6760584
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: