当前位置: 移动技术网 > IT编程>开发语言>c# > C#读写INI文件的方法

C#读写INI文件的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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();
    }
    catch
    {
     throw (new applicationexception("ini文件不存在"));
    }
   }
   //必须是完全路径,不能是相对路径
   filename = fileinfo.fullname;
  }
  //写ini文件
  public void writestring(string section, string ident, string value)
  {
   if (!writeprivateprofilestring(section, ident, value, filename))
   {
    throw (new applicationexception("写ini文件出错"));
   }
  }
  //读取ini文件指定
  public string readstring(string section, string ident, string default)
  {
   byte[] buffer = new byte[65535];
   int buflen = getprivateprofilestring(section, ident, default, buffer, buffer.getupperbound(0), filename);
   //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
   string s = encoding.getencoding(0).getstring(buffer);
   s = s.substring(0, buflen);
   return s.trim();
  }
  //读整数
  public int readinteger(string section, string ident, int default)
  {
   string intstr = readstring(section, ident, convert.tostring(default));
   try
   {
    return convert.toint32(intstr);
   }
   catch (exception ex)
   {
    console.writeline(ex.message);
    return default;
   }
  }
  //写整数
  public void writeinteger(string section, string ident, int value)
  {
   writestring(section, ident, value.tostring());
  }
  //读布尔
  public bool readbool(string section, string ident, bool default)
  {
   try
   {
    return convert.toboolean(readstring(section, ident, convert.tostring(default)));
   }
   catch (exception ex)
   {
    console.writeline(ex.message);
    return default;
   }
  }
  //写bool
  public void writebool(string section, string ident, bool value)
  {
   writestring(section, ident, convert.tostring(value));
  }
  //从ini文件中,将指定的section名称中的所有ident添加到列表中
  public void readsection(string section, stringcollection idents)
  {
   byte[] buffer = new byte[16384];
   //idents.clear();
   int buflen = getprivateprofilestring(section, null, null, buffer, buffer.getupperbound(0),
     filename);
   //对section进行解析
   getstringsfrombuffer(buffer, buflen, idents);
  }
  private void getstringsfrombuffer(byte[] buffer, int buflen, stringcollection strings)
  {
   strings.clear();
   if (buflen != 0)
   {
    int start = 0;
    for (int i = 0; i < buflen; i++)
    {
     if ((buffer[i] == 0) && ((i - start) > 0))
     {
      string s = encoding.getencoding(0).getstring(buffer, start, i - start);
      strings.add(s);
      start = i + 1;
     }
    }
   }
  }
  //从ini文件中,读取所有的sections的名称
  public void readsections(stringcollection sectionlist)
  {
   //note:必须得用bytes来实现,stringbuilder只能取到第一个section
   byte[] buffer = new byte[65535];
   int buflen = 0;
   buflen = getprivateprofilestring(null, null, null, buffer,
    buffer.getupperbound(0), filename);
   getstringsfrombuffer(buffer, buflen, sectionlist);
  }
  //读取指定的section的所有value到列表中
  public void readsectionvalues(string section, namevaluecollection values)
  {
   stringcollection keylist = new stringcollection();
   readsection(section, keylist);
   values.clear();
   foreach (string key in keylist)
   {
    values.add(key, readstring(section, key, ""));
   }
  }
  ////读取指定的section的所有value到列表中,
  //public void readsectionvalues(string section, namevaluecollection values,char splitstring)
  //{  string sectionvalue;
  //  string[] sectionvaluesplit;
  //  stringcollection keylist = new stringcollection();
  //  readsection(section, keylist);
  //  values.clear();
  //  foreach (string key in keylist)
  //  {
  //    sectionvalue=readstring(section, key, "");
  //    sectionvaluesplit=sectionvalue.split(splitstring);
  //    values.add(key, sectionvaluesplit[0].tostring(),sectionvaluesplit[1].tostring());
  //  }
  //}
  //清除某个section
  public void erasesection(string section)
  {
   if (!writeprivateprofilestring(section, null, null, filename))
   {
    throw (new applicationexception("无法清除ini文件中的section"));
   }
  }
  //删除某个section下的键
  public void deletekey(string section, string ident)
  {
   writeprivateprofilestring(section, ident, null, filename);
  }
  //note:对于win9x,来说需要实现updatefile方法将缓冲中的数据写入文件
  //在win nt, 2000和xp上,都是直接写文件,没有缓冲,所以,无须实现updatefile
  //执行完对ini文件的修改之后,应该调用本方法更新缓冲区。
  public void updatefile()
  {
   writeprivateprofilestring(null, null, null, filename);
  }
  //检查某个section下的某个键值是否存在
  public bool valueexists(string section, string ident)
  {
   stringcollection idents = new stringcollection();
   readsection(section, idents);
   return idents.indexof(ident) > -1;
  }
  //确保资源的释放
  ~inifiles()
  {
   updatefile();
  }
 }
}

目前c# 对ini文件操作基本上要被xml文件取代了,但是我觉得ini文件的读写仍然是编程的基本,是必须会的

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网