C# INI文件读写

C# INI文件读写

在对ini文件读写时,需要借助Windows的API函数实现,因此在SetConfigHelper类中引入了相关的API函数。声明API函数时,需要添加System.Runtime.InteropServices命名空间。

1. 命名空间

using System.Runtime.InteropServices;
using System.Windows.Forms;

2. INI文件读写操作接口类

public class SetConfigHelper
	{
		[DllImport("kernel32.dll")]
		private static extern long WritePrivateProfileString(string section, string key, string value, string filepath);

		[DllImport("Kernel32.dll")]
		private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);

		public string IniFilePath = System.Windows.Forms.Application.StartupPath + @"\Configs" + "\\Set.ini";//设置INI配置文件的路径,默认
		
		public static void WriteIni(string Section, string key, string msg)
		{
			try
			{
				WritePrivateProfileString(Section, key, msg, IniFilePath);
			}
			catch (Exception e)
			{
				MessageBox.Show(e.Message);
			}
		}
		
		private static void GetValue(string section, string key, out string value)
		{
			Byte[] Buffer = new Byte[65535];
			int bufLen = GetPrivateProfileString(section, key, "", Buffer, Buffer.GetUpperBound(0), IniFilePath);
			//为支持中文必须设定0(系统默认的代码页)的编码方式
			string s = Encoding.GetEncoding(0).GetString(Buffer);
			s = s.Substring(0, bufLen);
			value = s.Trim().Contains('\0') ? (s.Trim().Split('\0')[0]) : (s.Trim());
		}

		public static string ReadIni(string Section, string key)
		{
			string outString = "";
			try
			{
				GetValue(Section, key, out outString);
			}
			catch (Exception e)
			{
				MessageBox.Show(e.Message);
			}
			return outString;
		}
	}

3.使用

如INI文件中的内容为:

[字段A]
Name=小明
Age=12
Height=150cm
Weight=40kg

[字段B]
Father=工程师
Mother=老师

定义变量:

string szName;
string szAge;
string szHeight;
string szWeight;
string szFather;
string szMother;

读INI文件,即获取ini文件中的值

public void LoadIni(string filename)
{
		SetConfigHelper.IniFilePath = filename;
		szName = SetConfigHelper.ReadIni("字段A", "Name");
		szAge = SetConfigHelper.ReadIni("字段A", "Age");
		szHeight = SetConfigHelper.ReadIni("字段A", "Height");
		szWeight = SetConfigHelper.ReadIni("字段A", "Weight");
		szFather = SetConfigHelper.ReadIni("字段B", "Father");
		szMother = SetConfigHelper.ReadIni("字段B", "Mother");
}

写INI文件,即将变量的值保存在ini文件中

public void SaveIni()
{
		SetConfigHelper.WriteIni("字段A", "Name", szName );
		SetConfigHelper.WriteIni("字段A", "Age", szAge );
		SetConfigHelper.WriteIni("字段A", "Height", szHeight );
		SetConfigHelper.WriteIni("字段A", "Weight", szWeight );
		SetConfigHelper.WriteIni("字段B", "Father", szFather );
		SetConfigHelper.WriteIni("字段B", "Mother", szMother );
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值