易采站长站为您分析C#读写INI文件的方法,涉及C#读写ini文件的相关实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下
本文实例讲述了C#读写INI文件的方法。。具体如下:
虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。
INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)
[Section]
Key=Value
VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类,从网上收集的,很全,就是没有对section的改名功能,高手可以增加一个。
- using System; using System.IO;
- using System.Runtime.InteropServices; using System.Text;
- using System.Collections; using System.Collections.Specialized;
- namespace wuyisky {
- /// <summary> /// IniFiles的类
- /// </summary> public class IniFiles
- { public string FileName; //INI文件名
- //声明读写INI文件的API函数 [DllImport("kernel32")]
- private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")]
- private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath); //类的构造函数,传递INI文件名
- public IniFiles(string AFileName) {
- // 判断文件是否存在 FileInfo fileInfo = new FileInfo(AFileName);
- //Todo:搞清枚举的用法 if ((!fileInfo.Exists))
- { //|| (FileAttributes.Directory in fileInfo.Attributes)) //文件不存在,建立文件
- System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default); try
- { sw.Write("#表格配置档案");
- sw.Close(); }










