C#读写INI文件

ZDNet软件频道 时间:2002-10-10 作者:盛放 |  我要评论()
本文关键词:shengfang
虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。
虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。

INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)

  [Section]

  Key=Value

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。

INIFILE类:

using System;

using System.IO;

using System.Runtime.InteropServices;

因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。

using System.Text;

namespace Ini

{

     publicclass IniFile

     {

         publicstring path;     //INI文件名

          [DllImport("kernel32")]

          privatestaticexternlong WritePrivateProfileString(string section,string key,string val,string filePath);

          [DllImport("kernel32")]

          privatestaticexternint GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);

         //声明读写INI文件的API函数    

         public IniFile(string INIPath)

         {

              path = INIPath;

         }

         //类的构造函数,传递INI文件名

         publicvoid IniWriteValue(string Section,string Key,string Value)

         {

              WritePrivateProfileString(Section,Key,Value,this.path);

         }

         //写INI文件        

         publicstring IniReadValue(string Section,string Key)

         {

              StringBuilder temp = new StringBuilder(255);

              int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);

              return temp.ToString();

         }

         //读取INI文件指定

     }

}


百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134