C# 读取ini配置文件

作者: 盛放 http://oraasp.vicp.net/article/article.aspx?ID=26


虽然微软早已经建议在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 UnityEngine;
using System.Collections;
using System.Text;
using System.Runtime.InteropServices;

namespace Ini
{
	public class IniFileReference
	{	
		//INI文件名
		private string path;				
	
		//声明读写INI文件的API函数
		[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文件名
		public IniFileReference(string INIPath)
		{
			path = INIPath;
		}

		//写INI文件
		public void IniWriteValue(string Section,string Key,string Value)
		{
			WritePrivateProfileString(Section,Key,Value,this.path);
		}
	
		//读取INI文件指定
		public string IniReadValue(string Section,string Key)
		{
			StringBuilder temp = new StringBuilder(255);
			int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);
			return temp.ToString();
		}
	}
}

调用方法

	private void SetBezierPoints()
	{
		_iniFile = new Ini.IniFileReference(Application.dataPath+"/Geometry.ini");

		for (int i = 0; i < _verCtrls; i++)
			for (int j = 0; j < _horCtrls; j++)
		{

			float x = float.Parse( _iniFile.IniReadValue("Points",(j + i * _horCtrls).ToString() + "x"));
			float y = float.Parse( _iniFile.IniReadValue("Points",(j + i * _horCtrls).ToString() + "y"));
		
			BezierReference.SetBezierPoints(j, i, x, y);
		}

	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值