C# 操作INI配置文件

来源:互联网 发布:系统反间谍软件 编辑:程序博客网 时间:2024/04/28 07:00

重构YH是遇到这个一样问题,就是YH前台页面的按钮要求实现客户自定义,客户可以跟随自己的喜好安排每个按钮的功能,所以,在每一次客户登陆是就需要初始化客户自定义排版,这里就需要用到初始化文件——INI

 .ini 文件是Initialization File的缩写,即初始化文件。是windows的系统配置文件所采用的存储格式,统管windows的各项配置,一般用户就用windows提供的各项图形化管理界面就可实现相同的配置了,但在某些情况,还是要直接编辑.ini才方便,一般只有很熟悉windows才能去直接编辑。开始时用于WIN3X下面,WIN95用注册表代替,以及后面的内容表示一个节,相当于注册表中的键。

除了windows现在很多其他操作系统下面的应用软件也有.ini文件,用来配置应用软件以实现不同用户的要求。一般不用直接编辑这些.ini文件,应用程序的图形界面即可操作以实现相同的功能。它可以用来存放软件信息,注册表信息等。

INI文件由节、键、值组成。

  [section]

参数(键=值)

  name=value

既然ini文件在初始化中使用,那么免不了的需要对它进行一些写入读取修改的操作,当然,这些东西window已经帮我们封装好了,我们只需要调用就可以了。很easy

Ini使用到的一些API函数:

 

[html] view plain copy
  1. #region 调用windowsAPI  
  2.        //用来读取INI 文件的内容  
  3.        [DllImport("Kernel32.dll")]  
  4.        private static extern int GetPrivateProfileString(string strAppName,string strKeyName,string strDefault,StringBuilder sbReturnString,int nSize,string strFileName);   
  5.        //返回所读取的字符串值的真实长度  
  6.        [DllImport("Kernel32.dll")]  
  7.        private extern static int GetPrivateProfileStringA(string strAppName, string strKeyName, string sDefault, byte[] buffer, int nSize, string strFileName);  
  8.        [DllImport("Kernel32.dll")]  
  9.        private static extern int GetPrivateProfileInt(string strAppName, string strKeyName, int nDefault, string strFileName);  
  10.        //获取ini文件所有的section  
  11.        [DllImport("Kernel32.dll")]  
  12.        private extern static int GetPrivateProfileSectionNamesA(byte[] buffer, int iLen, string fileName);  
  13.        //获取指定Section的key和value          
  14.        [System.Runtime.InteropServices.DllImport("Kernel32.dll")]  
  15.        private static extern int GetPrivateProfileSection(string lpAppName,byte[] lpReturnedString, int nSize,string lpFileName);   
  16.        //根据传入参数的不同进行写入或修改或删除操作(返回值 Long,非零表示成功,零表示失败)  
  17.        [DllImport("Kernel32.dll")]  
  18.        public static extern long WritePrivateProfileString(string strAppName, string strKeyName, string strKeyValue, string strFileName);  
  19.        //添加一个section内容列表  
  20.        [DllImport("Kernel32.dll")]  
  21.        public static extern long WritePrivateProfileSection(string strAppName, string strkeyandvalue, string strFileName);  
  22.        #endregion  


 

调用这些函数的所用到的方法:

[html] view plain copy
  1. #region 供UI调用的方法   
  2.   
  3.         /// <summary>  
  4.         /// 判断该ini文件是否存在如果不存在新建一个该文件  
  5.         /// </summary>  
  6.         public void FileExists()  
  7.         {  
  8.             try  
  9.             {  
  10.                 if (!File.Exists(this.filePath))  
  11.                 {  
  12.                     using (FileStream fs = File.Create(this.filePath))  
  13.                     {  
  14.                         fs.Close();  
  15.                     }  
  16.                 }  
  17.              }  
  18.             catch(Exception e)  
  19.             {  
  20.   
  21.             }  
  22.         }  
  23.   
  24.         /// <summary>  
  25.         /// 返回该配置文件中所有Section名称的集合  
  26.         /// </summary>  
  27.         /// <returns></returns>  
  28.         public ArrayList ReadSections()  
  29.         {  
  30.             byte[] buffer = new byte[65535];  
  31.             int rel = GetPrivateProfileSectionNamesA(buffer, buffer.GetUpperBound(0), this.filePath);  
  32.             int iCnt, iPos;  
  33.             ArrayList arrayList = new ArrayList();  
  34.             string tmp;  
  35.             if (rel > 0)  
  36.             {  
  37.                 iCnt = 0iPos = 0;  
  38.                 for (iCnt = 0; iCnt < rel; iCnt++)  
  39.                 {  
  40.                     if (buffer[iCnt] == 0x00)  
  41.                     {  
  42.                         tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();  
  43.                         iPos = iCnt + 1;  
  44.                         if (tmp != "")  
  45.                             arrayList.Add(tmp);  
  46.                     }  
  47.                 }  
  48.             }  
  49.             return arrayList;  
  50.         }  
  51.           
  52.         /// <summary>  
  53.         ///  获取指定节点的所有KEY的名称  
  54.         /// </summary>  
  55.         /// <param name="sectionName"></param>  
  56.         /// <returns></returns>  
  57.         public ArrayList ReadKeys(string sectionName)  
  58.         {  
  59.   
  60.             byte[] buffer = new byte[5120];  
  61.             int rel = GetPrivateProfileStringA(sectionName, null, "", buffer, buffer.GetUpperBound(0), this.filePath);  
  62.   
  63.             int iCnt, iPos;  
  64.             ArrayList arrayList = new ArrayList();  
  65.             string tmp;  
  66.             if (rel > 0)  
  67.             {  
  68.                 iCnt = 0iPos = 0;  
  69.                 for (iCnt = 0; iCnt < rel; iCnt++)  
  70.                 {  
  71.                     if (buffer[iCnt] == 0x00)  
  72.                     {  
  73.                         tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();  
  74.                         iPos = iCnt + 1;  
  75.                         if (tmp != "")  
  76.                             arrayList.Add(tmp);  
  77.                     }  
  78.                 }  
  79.             }  
  80.             return arrayList;  
  81.         }  
  82.   
  83.         /// <summary>  
  84.         /// 读取指定节点下的指定key的value返回string  
  85.         /// </summary>  
  86.         /// <param name="section"></param>  
  87.         /// <param name="key">param>  
  88.         /// <returns></returns>  
  89.         public string GetIniKeyValueForStr(string section, string key)  
  90.         {  
  91.             if (section.Trim().Length <= 0 || key.Trim().Length <= 0) return string.Empty;  
  92.             StringBuilder strTemp = new StringBuilder(256);  
  93.             GetPrivateProfileString(section, key, string.Empty, strTemp, 256, this.filePath);  
  94.             return strTemp.ToString().Trim();  
  95.         }  
  96.   
  97.         /// <summary>  
  98.         /// 从指定的节点中获取一个整数值( Long,找到的key的值;如指定的key未找到,就返回默认值。如找到的数字不是一个合法的整数,函数会返回其中合法的一部分。如,对于“xyz=55zz”这个条目,函数返回55。)  
  99.         /// </summary>  
  100.         /// <param name="section"></param>  
  101.         /// <param name="key"></param>  
  102.         /// <returns></returns>  
  103.         public int GetIniKeyValueForInt(string section, string key)  
  104.         {  
  105.             if (section.Trim().Length <= 0 || key.Trim().Length <= 0) return 0;  
  106.             return GetPrivateProfileInt(section, key, 0, this.filePath);  
  107.         }  
  108.   
  109.         /// <summary>  
  110.         /// 读取指定节点下的所有key 和value  
  111.         /// </summary>  
  112.         /// <param name="section"></param>  
  113.         /// <returns></returns>  
  114.         public ArrayList GetIniSectionValue(string section)  
  115.         {  
  116.             byte[] buffer = new byte[5120];  
  117.             int rel = GetPrivateProfileSection(section, buffer, buffer.GetUpperBound(0), this.filePath);  
  118.   
  119.             int iCnt, iPos;  
  120.             ArrayList arrayList = new ArrayList();  
  121.             string tmp;  
  122.             if (rel > 0)  
  123.             {  
  124.                 iCnt = 0iPos = 0;  
  125.                 for (iCnt = 0; iCnt < rel; iCnt++)  
  126.                 {  
  127.                     if (buffer[iCnt] == 0x00)  
  128.                     {  
  129.                         tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();  
  130.                         iPos = iCnt + 1;  
  131.                         if (tmp != "")  
  132.                             arrayList.Add(tmp);  
  133.                     }  
  134.                 }  
  135.             }  
  136.             return arrayList;  
  137.         }  
  138.   
  139.         /// <summary>  
  140.         /// 往指定section的key中写入value  
  141.         /// </summary>  
  142.         /// <param name="section"></param>  
  143.         /// <param name="key"></param>  
  144.         /// <param name="value"></param>  
  145.         /// <returns></returns>  
  146.         public bool WriteIniKey(string section, string key, string value)  
  147.         {  
  148.             try  
  149.             {  
  150.                 if (section.Trim().Length <= 0 || key.Trim().Length <= 0 || value.Trim().Length <= 0)  
  151.                 {  
  152.                     flag = false;  
  153.                 }  
  154.                 else  
  155.                 {  
  156.                     
  157.                     if (WritePrivateProfileString(section, key, value, this.filePath) == 0)  
  158.                     {  
  159.                         flag = false;  
  160.                     }  
  161.                     else  
  162.                     {  
  163.                         flag = true;  
  164.                     }  
  165.                 }  
  166.             }  
  167.             catch  
  168.             {  
  169.                 flag = false;  
  170.             }  
  171.             return flag;  
  172.         }  
  173.   
  174.         /// <summary>  
  175.         /// 修改指定section的key的值  
  176.         /// </summary>  
  177.         /// <param name="section"></param>  
  178.         /// <param name="key"></param>  
  179.         /// <param name="value"></param>  
  180.         /// <returns></returns>  
  181.         public bool EditIniKey(string section, string key, string value)  
  182.         {  
  183.             try  
  184.             {  
  185.                 if (section.Trim().Length <= 0 || key.Trim().Length <= 0 || value.Trim().Length <= 0)  
  186.                 {  
  187.                     flag = false;  
  188.                 }  
  189.                 else  
  190.                 {  
  191.                     if (WritePrivateProfileString(section, key, value, this.filePath) == 0)  
  192.                     {  
  193.                         flag = false;  
  194.                     }  
  195.                     else  
  196.                     {  
  197.                         flag = true;  
  198.                     }  
  199.                 }  
  200.             }  
  201.             catch  
  202.             {  
  203.                 flag = false;  
  204.             }  
  205.             return flag;  
  206.         }  
  207.   
  208.         /// <summary>  
  209.         /// 删除指定section的指定key  
  210.         /// </summary>  
  211.         /// <param name="section"></param>  
  212.         /// <param name="key"></param>  
  213.         /// <returns></returns>  
  214.         public bool DeleteIniKey(string section, string key)  
  215.         {  
  216.             try  
  217.             {  
  218.                 if (section.Trim().Length <= 0 || key.Trim().Length <= 0)  
  219.                 {  
  220.                     flag = false;  
  221.                 }  
  222.                 else  
  223.                 {  
  224.                     if (WritePrivateProfileString(section, key, null, this.filePath) == 0)  
  225.                     {  
  226.                         flag = false;  
  227.                     }  
  228.                     else  
  229.                     {  
  230.                         flag = true;  
  231.                     }  
  232.                 }  
  233.             }  
  234.             catch  
  235.             {  
  236.                 flag = false;  
  237.             }  
  238.             return flag;  
  239.         }  
  240.   
  241.         /// <summary>  
  242.         /// 删除指定section  
  243.         /// </summary>  
  244.         /// <param name="section"></param>  
  245.         /// <returns></returns>  
  246.         public bool DeleteIniSection(string section)  
  247.         {  
  248.             try  
  249.             {  
  250.                 if (section.Trim().Length <= 0)  
  251.                 {  
  252.                     flag = false;  
  253.                 }  
  254.                 else  
  255.                 {  
  256.                     if (WritePrivateProfileString(section, null, null, this.filePath) == 0)  
  257.                     {  
  258.                         flag = false;  
  259.                     }  
  260.                     else  
  261.                     {  
  262.                         flag = true;  
  263.                     }  
  264.                 }  
  265.             }  
  266.             catch  
  267.             {  
  268.                 flag = false;  
  269.             }  
  270.             return flag;  
  271.         }  
  272.   
  273.         /// <summary>  
  274.         /// 给一个节点写入key和value列表  
  275.         /// </summary>  
  276.         /// <param name="section"></param>  
  277.         /// <param name="ht"></param>  
  278.         /// <returns></returns>  
  279.         public bool WriteIniSectionAndValue(string section, Hashtable ht)  
  280.         {  
  281.             string lpString = "";  
  282.             try  
  283.             {  
  284.                 if (section.Trim().Length <= 0 || ht.Count == 0)  
  285.                 {  
  286.                     flag = false;  
  287.                 }  
  288.                 else  
  289.                 {  
  290.                     foreach (DictionaryEntry de in ht)  
  291.                     {  
  292.                         lpString += de.Key+"="+de.Value;                        
  293.                         lpString += "\r\n";  
  294.                     }  
  295.                     if (WritePrivateProfileSection(section, lpString, this.filePath) == 0)  
  296.                     {  
  297.                         flag = false;  
  298.                     }  
  299.                     else  
  300.                     {  
  301.                         flag = true;  
  302.                     }  
  303.   
  304.                 }  
  305.             }  
  306.             catch  
  307.             {  
  308.                 flag = false;  
  309.             }  
  310.             return flag;  
  311.         }  
  312.          
  313.         /// <summary>  
  314.         /// 给一个节点写入key 列表  
  315.         /// </summary>  
  316.         /// <param name="section"></param>  
  317.         /// <param name="lstKeyValue"></param>  
  318.         /// <returns></returns>  
  319.         public bool WriteIniSectionName(string section, List<string> lstKeyValue)  
  320.         {  
  321.             string lpString = "";  
  322.             try  
  323.             {  
  324.                 if (section.Trim().Length <= 0 || lstKeyValue.Count == 0)  
  325.                 {  
  326.                     flag = false;  
  327.                 }  
  328.                 else  
  329.                 {  
  330.                     for (int i = 0; i < lstKeyValue.Count; ++i)  
  331.                     {  
  332.                         lpString += lstKeyValue[i];  
  333.                         lpString += "\r\n";  
  334.                     }  
  335.                     if (WritePrivateProfileSection(section, lpString, this.filePath) == 0)  
  336.                     {  
  337.                         flag = false;  
  338.                     }  
  339.                     else  
  340.                     {  
  341.                         flag = true;  
  342.                     }  
  343.   
  344.                 }  
  345.             }  
  346.             catch  
  347.             {  
  348.                 flag = false;  
  349.             }  
  350.             return flag;  
  351.         }  
  352.         #endregion  


 

U层,我们需要

[html] view plain copy
  1. //创建一个INIFile对象,参数为文件路径  
  2.         ManagerConfigIni iniConfig = new ManagerConfigIni(AppDomain.CurrentDomain.BaseDirectory + @"\配置.ini");  


 

然后通过相应的事件,来调用对应的方法即可。

 

 

如果 ini 中没有指定的 SectionAPI会新建 Section,如果没有指定的 Key则新建一个 Key 并写入数据,如果已经存在,则用字符串代替原来的值。当指定的 ini也不存在的时候,API会自动建立一个新的文件,所以使用 ini的好处是我们不必为了保存少量的数据涉及到文件操作,就连查找文件是否存在的操作都不必要。

使用要点:在我们实际使用的时候,用的最多的是 GetPrivateProfileString WritePrivateProfileString,但在对自定义 ini文件操作的时候要注意的是,如果 lpFileName 指定的文件没有路径的话,Api会去 Windows的安装目录去找而不会在当前目录找,但是每次用到 ini函数要获取当前路径显然太麻烦了,这里有一个变通的办法,你只要在 ini文件名前面加上 .\ 就可以了,比如说要对本目录下的 user.ini操作,那么文件名就是 '.\user.ini'这样显然比较方便。另外,当你要把一个 Key清除的时候,可以使用把 lpString指向一个空的字符串然后使用 WritePrivateProfileString。当你要把一个 section的全部内容清空的时候,也不必把 key一个个的清除,可以使用把 lpString指向一个空的字符串然后使用 WritePrivateProfileSection INI文件就是扩展名为“ini”的文件。在Windows系统中,INI文件是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。该文件主要存放用户所做的选择以及系统的各种参数。用户可以通过修改INI文件,来改变应用程序和系统的很多配置。但自从Windows 95的退出,在Windows系统中引入了注册表的概念,INI文件在Windows系统的地位就开始不断下滑,这是因为注册表的独特优点,使应用程序和系统都把许多参数和初始化信息放进了注册表中。


http://blog.csdn.net/laner0515/article/details/8439933

0 0
原创粉丝点击