欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# Ini文件操作实例

程序员文章站 2024-02-24 22:51:40
在开源中国看到的操作ini文件的,写的还不看,留着以后用复制代码 代码如下:using system;using system.io;using system.runtim...

在开源中国看到的操作ini文件的,写的还不看,留着以后用

复制代码 代码如下:

using system;
using system.io;
using system.runtime.interopservices;
using system.text;
using system.collections;
using system.collections.specialized;

namespace *sky{
  /**//**/
  /**//// <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();
    }
  }
}