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 );
}

猜你喜欢

转载自blog.csdn.net/CXYLVCHF/article/details/111224305
今日推荐