• C# ini 文件操作类代码及参考注释


    此类是操作ini文件的,但不限于ini文件,如也可以操作.db文件,只需将文件后缀名改为.db即可,不需要改动代码。

      1 using System;
      2 using System.IO;
      3 using System.Runtime.InteropServices;
      4 using System.Text;
      5 using System.Collections;
      6 using System.Collections.Specialized;
      7 using System.Windows.Forms;
      8 
      9 namespace firsttest
     10 {
     11     /// <summary>
     12     /// 修订:1.1 修正了对中文系统的支持。
     13     /// 1.2 增加了UpdateFile方法,实现了对Win9x的支持
     14     /// 1.3 增加了读写布尔,整数的操作
     15     /// 1.4 修正了写Ini虽然成功,但是会抛出异常的错误
     16     /// 1.5 ReadString返回的是Trim后的字符串
     17     /// 1.6 统一并扩大了读写缓冲区的大小
     18     /// </summary>
     19     public class INIOperator
     20     {
     21 
     22         public string FileName; //INI文件名
     23         //声明读写INI文件的API函数
     24         [DllImport("kernel32")]
     25         private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
     26         [DllImport("kernel32")]
     27         private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
     28 
     29 
     30         //类的构造函数,传递INI文件名
     31         public INIOperator(string AFileName)
     32         {
     33             // 判断文件是否存在
     34             FileInfo fileInfo = new FileInfo(AFileName);
     35 
     36             //Todo:搞清枚举的用法
     37             if ((!fileInfo.Exists)) //|| (FileAttributes.Directory in fileInfo.Attributes))
     38             {
     39                 //throw (new ApplicationException("Ini文件不存在"));
     40 
     41                 File.CreateText(AFileName).Close();
     42             }
     43             //必须是完全路径,不能是相对路径
     44             FileName = fileInfo.FullName;
     45         }
     46         //写INI文件
     47         public void WriteString(string Section, string Ident, string Value)
     48         {
     49             if (!WritePrivateProfileString(Section, Ident, Value, FileName))
     50             {
     51                 // Todo:抛出自定义的异常
     52                 throw (new ApplicationException("写Ini文件出错"));
     53             }
     54         }
     55         //读取INI文件指定
     56         public string ReadString(string Section, string Ident, string Default)
     57         {
     58             //StringBuilder Buffer = new StringBuilder(255);
     59             Byte[] Buffer = new Byte[65535];
     60             int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
     61             //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
     62             string s = Encoding.GetEncoding(0).GetString(Buffer);
     63             s = s.Substring(0, bufLen);
     64             return s.Trim();
     65         }
     66 
     67         //读整数
     68         public int ReadInteger(string Section, string Ident, int Default)
     69         {
     70             string intStr = ReadString(Section, Ident, Convert.ToString(Default));
     71             try
     72             {
     73                 return Convert.ToInt32(intStr);
     74             }
     75             catch (Exception ex)
     76             {
     77                 Console.WriteLine(ex.Message);
     78                 return Default;
     79             }
     80         }
     81 
     82         //写整数
     83         public void WriteInteger(string Section, string Ident, int Value)
     84         {
     85             WriteString(Section, Ident, Value.ToString());
     86         }
     87 
     88         //读布尔
     89         public bool ReadBool(string Section, string Ident, bool Default)
     90         {
     91             try
     92             {
     93                 return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
     94             }
     95             catch (Exception ex)
     96             {
     97                 Console.WriteLine(ex.Message);
     98                 return Default;
     99             }
    100         }
    101 
    102         //写Bool
    103         public void WriteBool(string Section, string Ident, bool Value)
    104         {
    105             WriteString(Section, Ident, Convert.ToString(Value));
    106         }
    107 
    108         //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
    109         public void ReadSection(string Section, StringCollection Idents)
    110         {
    111             Byte[] Buffer = new Byte[32768];
    112             //Idents.Clear();
    113 
    114             int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),
    115             FileName);
    116             //对Section进行解析
    117             GetStringsFromBuffer(Buffer, bufLen, Idents);
    118         }
    119 
    120         private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
    121         {
    122             Strings.Clear();
    123             if (bufLen != 0)
    124             {
    125                 int start = 0;
    126                 for (int i = 0; i < bufLen; i++)
    127                 {
    128                     if ((Buffer[i] == 0) && ((i - start) > 0))
    129                     {
    130                         String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
    131                         Strings.Add(s);
    132                         start = i + 1;
    133                     }
    134                 }
    135             }
    136         }
    137         //从Ini文件中,读取所有的Sections的名称
    138         public void ReadSections(StringCollection SectionList)
    139         {
    140             //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
    141             byte[] Buffer = new byte[65535];
    142             int bufLen = 0;
    143             bufLen = GetPrivateProfileString(null, null, null, Buffer,
    144             Buffer.GetUpperBound(0), FileName);
    145             GetStringsFromBuffer(Buffer, bufLen, SectionList);
    146         }
    147         //读取指定的Section的所有Value到列表中
    148         public void ReadSectionValues(string Section, NameValueCollection Values)
    149         {
    150             StringCollection KeyList = new StringCollection();
    151             ReadSection(Section, KeyList);
    152             Values.Clear();
    153             foreach (string key in KeyList)
    154             {
    155                 Values.Add(key, ReadString(Section, key, ""));
    156             }
    157         }
    158         //清除某个Section
    159         public void EraseSection(string Section)
    160         {
    161             //
    162             if (!WritePrivateProfileString(Section, null, null, FileName))
    163             {
    164                 throw (new ApplicationException("无法清除Ini文件中的Section"));
    165             }
    166         }
    167         //删除某个Section下的键
    168         public void DeleteKey(string Section, string Ident)
    169         {
    170             WritePrivateProfileString(Section, Ident, null, FileName);
    171         }
    172         //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
    173         //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
    174         //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
    175         public void UpdateFile()
    176         {
    177             WritePrivateProfileString(null, null, null, FileName);
    178         }
    179 
    180         //检查某个Section下的某个键值是否存在
    181         public bool ValueExists(string Section, string Ident)
    182         {
    183             //
    184             StringCollection Idents = new StringCollection();
    185             ReadSection(Section, Idents);
    186             return Idents.IndexOf(Ident) > -1;
    187         }
    188 
    189         //确保资源的释放
    190         ~INIOperator()
    191         {
    192             UpdateFile();
    193         }
    194     }
    195 }

    下面是Delphi ini文件的读写类的注释,感觉和C#中差不多,可作参考。

    (1) INI文件的结构: 

    ;这是关于INI文件的注释部分 

    [节点] 

    关键字=值 

    ... 

    INI文件允许有多个节点,每个节点又允许有多个关键字, “=”后面是该关键字的值(类型有三种:字符串、整型数值和布尔值。其中字符串存贮在INI文件中时没有引号,布尔真值用1表示,布尔假值用0表示)。注释以分号“;”开头。

    (2) INI文件的操作 

    1、 在Interface的Uses节增加IniFiles; 

    2、 在Var变量定义部分增加一行:inifile:Tinifile;然后,就可以对变量myinifile进行创建、打开、读取、写入等操作了。 

    3、 打开INI文件:inifile:=Tinifile.create('tmp.ini'); 

    4、 读取关键字的值:  a:=inifile.Readstring('节点','关键字',缺省值);// string类型  b:=inifile.Readinteger('节点','关键字',缺省值);// integer类型  c:=inifile.Readbool('节点','关键字',缺省值);// boolean类型  其中[缺省值]为该INI文件不存在该关键字时返回的缺省值。 

    5、 写入INI文件:  inifile.writestring('节点','关键字',变量或字符串值);  inifile.writeinteger('节点','关键字',变量或整型值);  inifile.writebool('节点','关键字',变量或True或False);  当这个INI文件的节点不存在时,上面的语句还会自动创建该INI文件。 

    6、 删除关键字:  inifile.DeleteKey('节点','关键字');//关键字删除  inifile.EraseSection('节点');// 节点删除 

    7、 节点操作:  inifile.readsection('节点',TStrings变量);//可将指定小节中的所有关键字名读取至一个字符串列表变量中;  inifile.readsections(TStrings变量);//可将INI文件中所有小节名读取至一个字符串列表变量中去。  inifile.readsectionvalues('节点',TStrings变量);//可将INI文件中指定小节的所有行(包括关键字、=、值)读取至一个字符串列表变量中去。 

    8、 释放:inifile.distory;或inifile.free;

     注释部分转自:http://www.cnblogs.com/zhangzhifeng/archive/2011/12/01/2270267.html

  • 相关阅读:
    剑指Offer
    剑指Offer
    剑指Offer
    面积(area)
    最少步数
    细胞
    集合的前N个元素
    1~100卡特兰数(存一下hhhh)
    [Codeforces137C]History(排序,水题)
    [Codeforces676B]Pyramid of Glasses(递推,DP)
  • 原文地址:https://www.cnblogs.com/fjfhxotfl/p/3420111.html
Copyright © 2020-2023  润新知