C# 读取INI
虽然微软早已经建议在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 的类的集合。
- using System.Text;
- namespace Ini
- {
- public class IniFile
- {
- public string path; //INI文件名
- [DllImport("kernel32")]
- private static extern long WritePrivateProfileString(string section,string key,
- string val,string filePath);
- [DllImport("kernel32")]
- private static extern int GetPrivateProfileString(string section,string key,string def,
- StringBuilder retVal,int size,string filePath);
- //声明读写INI文件的API函数
- public IniFile(string INIPath)
- {
- path = INIPath;
- }
- //类的构造函数,传递INI文件名
- publicvoid IniWriteValue(string Section,string Key,string Value)
- {
- WritePrivateProfileString(Section,Key,Value,this.path);
- }
- //写INI文件
- publicstring IniReadValue(string Section,string Key)
- {
- StringBuilder temp = new StringBuilder(255);
- int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);
- return temp.ToString();
- }
- //读取INI文件指定
- }
- }
调用INIFILE类:
新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。
增加如下代码:
using Ini; //创建命名空间 //当窗体关闭时保存窗体坐标
- privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
- {
- IniFile ini = new IniFile("C://test.ini");
- ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString());
- ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString());
- //ToString方法将数字转换为字符串
- }
//当窗体启动时,读取INI文件的值并赋值给窗体
- privatevoid Form1_Load(object sender, System.EventArgs e)
- {
- IniFile ini = new IniFile("C://test.ini");
- Point p=new Point();
- //判断返回值,避免第一次运行时为空出错
- if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))
- {
- p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));
- p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));
- // int.Parse将字符串转换为int
- this.Location =p;
- }
- }
==============================================
其他方法:
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);
- // 封装的方法中,最有价值的是获取所有Sections和所有的Keys,网上关于这个的代码大部分是错误的,这里给出一个正确的方法:
- /// 返回该配置文件中所有Section名称的集合
- public ArrayList ReadSections()
- {
- byte[] buffer = new byte[65535];
- int rel = 0;// GetPrivateProfileSectionNamesA(buffer, buffer.GetUpperBound(0), _FileName);
- int iCnt, iPos;
- ArrayList arrayList = new ArrayList();
- string tmp;
- if (rel > 0)
- {
- iCnt = 0; iPos = 0;
- for (iCnt = 0; iCnt < rel; iCnt++)
- {
- if (buffer[iCnt] == 0x00)
- {
- tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
- iPos = iCnt + 1;
- if (tmp != "")
- arrayList.Add(tmp);
- }
- }
- }
- return arrayList;
- }
- // 获取节点的所有KEY值
- public ArrayList ReadKeys(string sectionName)
- {
- byte[] buffer = new byte[5120];
- int rel = 0;// GetPrivateProfileStringA(sectionName, null, "", buffer, buffer.GetUpperBound(0), _FileName);
- int iCnt, iPos;
- ArrayList arrayList = new ArrayList();
- string tmp;
- if (rel > 0)
- {
- iCnt = 0; iPos = 0;
- for (iCnt = 0; iCnt < rel; iCnt++)
- {
- if (buffer[iCnt] == 0x00)
- {
- tmp = System.Text.ASCIIEncoding.Default.GetString(buffer, iPos, iCnt - iPos).Trim();
- iPos = iCnt + 1;
- if (tmp != "")
- arrayList.Add(tmp);
- }
- }
- }
- return arrayList;
- }
C# 读取INI的更多相关文章
- C#读取ini文件的方法
最近项目用到ini文件,读取ini文件,方法如下: using System; using System.Collections.Generic; using System.Linq; using S ...
- c#读取INI文件
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...
- c#读取INI文件类
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;na ...
- Java读取ini配置
本文转载地址: http://www.cnblogs.com/Jermaine/archive/2010/10/24/1859673.html 不够通用,呵呵. 读取ini的配置的格式如下 ...
- php读取ini配置文件属性
ini的内容格式如下,请根据自己的INI,格式修改下段程序. autostart = false font_size = font_color = red =================== fu ...
- VS VC 读取 INI文件
1.获取应程序同极目录下的config.ini路劲 void GetConfigFilePath(char *path,int len, char *file) { char module[256] ...
- C# 读取ini文件,读不出来原因
先赋上相关读取ini文件代码 public class INIHelper { public string inipath; [DllImport("kernel32")] pri ...
- C# 通过api函数GetPrivateProfileString读取ini文件,取不到值
通过api函数GetPrivateProfileString读取ini文件,取不到值,测试了好长时间,都不行 确认程序,ini文件都没有错误的情况,最后发现是ini文件编码的原因. 将ini文件的编码 ...
- Python读取ini配置文件的方式
python configparser模块 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...
随机推荐
- ImageView显示图像控件
ImageView显示图像控件 一.简介 1. 2. ImageView,图像视图,直接继承自View类,它的主要功能是用于显示图片,实际上它不仅仅可以用来显示图片,任何Drawable对象都可以使用 ...
- python运行httpserver
$ python -m SimpleHTTPServer $ python3 -m http.server
- 四十二 Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)的mget和bulk批量操作
注意:前面讲到的各种操作都是一次http请求操作一条数据,如果想要操作多条数据就会产生多次请求,所以就有了mget和bulk批量操作,mget和bulk批量操作是一次请求可以操作多条数据 1.mget ...
- sed、awk学习篇
[yongsan@yz6245 ~]$ awk 'BEGIN {FS=":"}{shells[$NF]++;}END{for(i in shells)print i ": ...
- [转载]java调用PageOffice生成word
一.在开发OA办公或与文档相关的Web系统中,难免会遇到动态生成word文档的需求,为了解决工作中遇到导出word文档的需求,前一段时间上网找了一些资料,在word导出这方面有很多工具可以使用,jac ...
- flask_sqlalchemy + sqlite 的一系列使用方法
如何使用在官网上有详细记录 :http://flask-sqlalchemy.pocoo.org/2.3/ 作为项目笔记,简单阐述使用方法: 1.创建flask_sqlalchemy基于sqlite的 ...
- Shell 参数(2) --解析命令行参数工具:getopts/getopt
getopt 与 getopts 都是 Bash 中用来获取与分析命令行参数的工具,常用在 Shell 脚本中被用来分析脚本参数. 两者的比较 (1)getopts 是 Shell 内建命令,geto ...
- SSH框架(2)
个人分类: Java面试 Struts 谈谈你对Struts的理解. 答: 1.struts是一个按MVC模式设计的Web层框架,其实它就是一个大大的servlet,这个Servlet名为Acti ...
- 重温CLR(六)方法和参数
实例构造器和类(引用类型) 构造器是将类型的实例初始化为良好状态的特殊方法.构造器方法在“方法定义元数据表”中始终叫做.ctor(constructor的简称).创建引用类型的实例时,首先为实例的数据 ...
- LOJ103 子串查找
题意 这是一道模板题. 给定一个字符串 A 和一个字符串 B ,求 B 在 A 中的出现次数.A 和 B 中的字符均为英语大写字母或小写字母. A 中不同位置出现的 B 可重叠. 分析 参照jklov ...