虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。

  INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value):

  [Section]
  Key=Value

VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。

INIFILE类:

using System;
using System.IO;
using System.Runtime.InteropServices;

因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。

  1. using System.Text;  
  2.   
  3. namespace Ini  
  4. {  
  5.     public class IniFile  
  6.     {  
  7.         public string path;             //INI文件名  
  8.   
  9.         [DllImport("kernel32")]  
  10.         private static extern long WritePrivateProfileString(string section,string key,  
  11.                     string val,string filePath);  
  12.   
  13.         [DllImport("kernel32")]  
  14.         private static extern int GetPrivateProfileString(string section,string key,string def,  
  15.                     StringBuilder retVal,int size,string filePath);  
  16.   
  17.         //声明读写INI文件的API函数  
  18.         public IniFile(string INIPath)  
  19.         {  
  20.             path = INIPath;  
  21.         }  
  22.   
  23.         //类的构造函数,传递INI文件名  
  24.         publicvoid IniWriteValue(string Section,string Key,string Value)  
  25.         {  
  26.             WritePrivateProfileString(Section,Key,Value,this.path);  
  27.         }  
  28.   
  29.         //写INI文件  
  30.         publicstring IniReadValue(string Section,string Key)  
  31.         {  
  32.             StringBuilder temp = new StringBuilder(255);  
  33.             int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);  
  34.             return temp.ToString();  
  35.         }  
  36.   
  37.         //读取INI文件指定  
  38.     }  
  39. }  
 

调用INIFILE类:

新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。

增加如下代码:

using Ini;			//创建命名空间

//当窗体关闭时保存窗体坐标
  1. privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  2. {
  3. IniFile ini = new IniFile("C://test.ini");
  4. ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString());
  5. ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString());
  6. //ToString方法将数字转换为字符串
  7. }
//当窗体启动时,读取INI文件的值并赋值给窗体
  1. privatevoid Form1_Load(object sender, System.EventArgs e)
  2. {
  3. IniFile ini = new IniFile("C://test.ini");
  4. Point p=new Point();
  5. //判断返回值,避免第一次运行时为空出错
  6. if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))
  7. {
  8. p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));
  9. p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));
  10. // int.Parse将字符串转换为int
  11. this.Location =p;
  12. }
  13. }
  
==============================================
其他方法:
DllImport("kernel32.dll")]
public extern static int GetPrivateProfileString(string segName, string keyName, string sDefault, StringBuilder buffer, int nSize, string fileName);

public extern static int GetPrivateProfileStringA(string segName, string keyName, string sDefault, byte[] buffer, int iLen, string fileName); // ANSI版本

[DllImport("kernel32.dll")]
public extern static int GetPrivateProfileSection(string segName, StringBuilder buffer, int nSize, string fileName);

[DllImport("kernel32.dll")]
public extern static int WritePrivateProfileSection(string segName, string sValue, string fileName);

[DllImport("kernel32.dll")]
public extern static int WritePrivateProfileString(string segName, string keyName, string sValue, string fileName);

[DllImport("kernel32.dll")]
public extern static int GetPrivateProfileSectionNamesA(byte[] buffer, int iLen, string fileName);

 
  1. // 封装的方法中,最有价值的是获取所有Sections和所有的Keys,网上关于这个的代码大部分是错误的,这里给出一个正确的方法:
  2. /// 返回该配置文件中所有Section名称的集合
  3. public ArrayList ReadSections()
  4. {
  5. byte[] buffer = new byte[65535];
  6. int rel = 0;// GetPrivateProfileSectionNamesA(buffer, buffer.GetUpperBound(0), _FileName);
  7. int iCnt, iPos;
  8. ArrayList arrayList = new ArrayList();
  9. string tmp;
  10. if (rel > 0)
  11. {
  12. iCnt = 0; iPos = 0;
  13. for (iCnt = 0; iCnt < rel; iCnt++)
  14. {
  15. if (buffer[iCnt] == 0x00)
  16. {
  17. tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
  18. iPos = iCnt + 1;
  19. if (tmp != "")
  20. arrayList.Add(tmp);
  21. }
  22. }
  23. }
  24. return arrayList;
  25. }
  26. // 获取节点的所有KEY值
  27. public ArrayList ReadKeys(string sectionName)
  28. {
  29. byte[] buffer = new byte[5120];
  30. int rel = 0;// GetPrivateProfileStringA(sectionName, null, "", buffer, buffer.GetUpperBound(0), _FileName);
  31. int iCnt, iPos;
  32. ArrayList arrayList = new ArrayList();
  33. string tmp;
  34. if (rel > 0)
  35. {
  36. iCnt = 0; iPos = 0;
  37. for (iCnt = 0; iCnt < rel; iCnt++)
  38. {
  39. if (buffer[iCnt] == 0x00)
  40. {
  41. tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
  42. iPos = iCnt + 1;
  43. if (tmp != "")
  44. arrayList.Add(tmp);
  45. }
  46. }
  47. }
  48. return arrayList;
  49. }
 
 

C# 读取INI的更多相关文章

  1. C#读取ini文件的方法

    最近项目用到ini文件,读取ini文件,方法如下: using System; using System.Collections.Generic; using System.Linq; using S ...

  2. c#读取INI文件

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  3. c#读取INI文件类

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;na ...

  4. Java读取ini配置

    本文转载地址:       http://www.cnblogs.com/Jermaine/archive/2010/10/24/1859673.html 不够通用,呵呵. 读取ini的配置的格式如下 ...

  5. php读取ini配置文件属性

    ini的内容格式如下,请根据自己的INI,格式修改下段程序. autostart = false font_size = font_color = red =================== fu ...

  6. VS VC 读取 INI文件

    1.获取应程序同极目录下的config.ini路劲 void GetConfigFilePath(char *path,int len, char *file) { char module[256] ...

  7. C# 读取ini文件,读不出来原因

    先赋上相关读取ini文件代码 public class INIHelper { public string inipath; [DllImport("kernel32")] pri ...

  8. C# 通过api函数GetPrivateProfileString读取ini文件,取不到值

    通过api函数GetPrivateProfileString读取ini文件,取不到值,测试了好长时间,都不行 确认程序,ini文件都没有错误的情况,最后发现是ini文件编码的原因. 将ini文件的编码 ...

  9. Python读取ini配置文件的方式

    python configparser模块   ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...

随机推荐

  1. 【python教程】Python IDE

    PyCharm PyCharm是由JetBrains打造的一款Python IDE. PyCharm具备一般 Python IDE 的功能,比如:调试.语法高亮.项目管理.代码跳转.智能提示.自动完成 ...

  2. 如何去除pycharm中代码下的波浪线

    Pycharm中新建一个工程,如果不经过配置,在该工程下创建模块写代码,通常是有波浪线的,这样看着很不美观 如何解决这种问题,通常有两种方法 方法一:点击右下角的图标,会出现一个Highlightin ...

  3. appium自动化测试(二)

    一. 获取应用包名和入口activity 获取应用包名和入口activity:aapt命令 aapt目录: 安卓sdk的build-tools目录下(如果要在cmd里直接运行,要配置环境变量,否则需要 ...

  4. 配置Nginx作为反向代理服务器

    最近在实习公司的开发一个项目,项目是前后端彻底分离的项目,前端项目和后端项目各监听着特定的端口号,显然不是80的通用端口,为了不在地址栏上输入IP+端口号的形式,我们可以使用Nginx作为反向代理服务 ...

  5. 【2018年全国多校算法寒假训练营练习比赛(第四场)-D】小明的挖矿之旅

    题目链接:https://www.nowcoder.com/acm/contest/76/D 做题时没注意到“无论出现在哪个格子”..题中也没说明一个格子只能经过一次,其实没有想象的复杂. 判断如果点 ...

  6. Java8_02_lambda表达式

    一.前言 这一节我们来了解下lambda表达式,主要关注以下几点: 行为参数化 匿名类 Lambda 表达式 方法 引用 二.行为参数化 1.概念 行为参数化(behavior parameteriz ...

  7. js控制iframe的刷新(页面局部刷新)

    今天遇到个问题,后台会员审核之后,页面内的会员审核状态要及时改变,但又不能指望用户手动刷新(用户体验很不好) 如果审核页面和显示审核状态时同在一个html页面的话,那么直接用js改变div内部的文本就 ...

  8. Compiling OpenGL games with the Flash C Compiler (FlasCC)

    Compiling OpenGL games with the Flash C Compiler (FlasCC) In this article I show how to use the Flas ...

  9. Kali Linux ettercap的使用

    ettercap是执行ARP欺骗嗅探的工具,通常用它来施行中间人攻击. 我还介绍过另一个arp欺骗工具-arpspoof 我使用的是Kali Linux 2.0:在开始使用ettercap之前,先配置 ...

  10. Java类和数据结构中常用的方法

    1.Object类里面常用的方法: protected Object clone()创建并返回此对象的一个副本. boolean equals(Object obj)指示其他某个对象是否与此对象“相等 ...