C#操作Ini文件类

来源:互联网 发布:类似于社交网络的电影 编辑:程序博客网 时间:2024/04/30 00:59

      在Windows系统中,INI文件是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。但在某些场合,INI文件还拥有其不可替代的地位。由于C#类库中并不包含读取ini文件,用C#读取ini文件,必要用到windows的API函数,所以在声明windows的API函数必须这样声明:

          //声明读写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文件结构

INI文件是一种按照特点方式排列的文本文件。每一个INI文件结构都非常类似,由若干段落(section)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键词(keyword)和一个等号,等号右边的就是关键字对应的值(value)。其一般形式如下:


  1. [Section1]  
  2. KeyWord1 = Valuel 
  3. KeyWord2 = Value2 
  4.  ……  
  5. [Section2]  
  6. KeyWord3 = Value3 
  7. KeyWord4 = Value4  
C#读取INI文件类

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




原创粉丝点击