您现在的位置是:首页 > C# > C#读写ini文件

C#读写ini文件

王递杰 2023年9月5日 C#

INI文件是一种配置文件格式,是Initialization file的缩写,即为初始化文件,通常用于Windows操作系统中的应用程序中。

INI结构非常简单,由节(Section)、键(key)、值(value)、注释(comments)组成的两层结构。

键值对用"="隔开,左边为键,右边为值,每个键值对都要归纳于段落中,段落必须写在"[]"里。注释则以分号";"开头。

如下是一个ini文件:zcsoft.ini

[Database]
DBMS=MSSMicrosoft SQL Server6.x
ServerName=
LogID=sa
Lock="RC"
DBParm="CursorLock='ReadOnly',CommitOnDisconnect='No'"
AutoCommit=False
Prompt=1
server=SQL SERVER
language=CH

[Update]
update_ip=192.168.0.111
updatenum=
update=N

[report]
open_type=P
date=
date_segment=今日

;---LED屏内容---
[wgt_led]
led_txt=需要发送的内容
led_txt1=需要发送的内容
led_txt2=需要发送的内容

代码实现读写:

public static string pathINI = AppDomain.CurrentDomain.BaseDirectory + "zcsoft.ini";

//读取和写入 ini文件
static void Main(string[] args)
{
	
	INIHelper iniHelper = new INIHelper(pathINI);
	string updateIp = iniHelper.ReadValue("Update", "update_ip");
	Console.WriteLine(updateIp); //输出:192.168.0.111
	
	//读取section中所有key
	Dictionary<string, string> ledDict = iniHelper.ReadValues("wgt_led");
	foreach (var item in ledDict)
	{
		Console.WriteLine($"{item.Key}--{item.Value}");
	}
	//输出:
	//led_txt--需要发送的内容
	//led_txt1--需要发送的内容
	//led_txt2--需要发送的内容


	//写入
	iniHelper.WriteValue("test", "my_name", "jack");
	iniHelper.WriteValue("test", "my_age", "25");
	iniHelper.WriteValue("test", "my_size", "18");

	//删除
	//iniHelper.RemoveKey("test", "my_size");
	//iniHelper.RemoveSection("test");

	Console.ReadKey();
}

INIHelper.cs文件

public class INIHelper
{
	private string FilePath;
	public string Path
	{
		get { return this.FilePath; }
		set
		{
			if (value.Substring(0, 1) == "\\" || value.Substring(0, 1) == "/")
			{
				this.FilePath = AppDomain.CurrentDomain + value;
			}
			else
			{
				this.FilePath = value;
			}
		}
	}
	public INIHelper(string _Path)
	{
		this.Path = _Path;
	}

	[DllImport("kernel32")]
	private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);

	[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
	private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);


	[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
	private static extern uint GetPrivateProfileStringList(string section, string key,string def, Byte[] retVal, int size, string filePath);

	//写入
	public void WriteValue(string section, string key, string Value)
	{
		WritePrivateProfileString(section, key, Value, this.FilePath);
	}

	//读取单个key
	public string ReadValue(string section, string key)
	{
		try
		{
			StringBuilder temp = new StringBuilder();
			int i = GetPrivateProfileString(section, key, "", temp, -1, this.FilePath);
			return temp.ToString();
		}
		catch { return ""; }
	}
	//读取section下的所有key
	public Dictionary<string,string> ReadValues(string section)
	{
		try
		{
			List<string> secList = new List<string>();
			Byte[] buf = new Byte[65536];
			uint len = GetPrivateProfileStringList(section, null, null, buf, buf.Length, this.FilePath);
			int j = 0;
			for (int i = 0; i < len; i++)
			{
				if (buf[i] == 0)
				{
					secList.Add(Encoding.Default.GetString(buf, j, i - j));
					j = i + 1;
				}
			}
			var dict = new Dictionary<string, string>();
			secList.ForEach(item =>
			{
				StringBuilder retVal = new StringBuilder();
				GetPrivateProfileString(section, item, "", retVal, -1, this.FilePath);
				dict.Add(item, retVal.ToString());
			});
			return dict;
		}
		catch { return null; }
	}

	//删除key
	public void RemoveKey(string section, string key)
	{
		WritePrivateProfileString(section, key, null, this.FilePath);
	}

	//删除key下的所有
	public bool RemoveSection(string section)
	{
		return WritePrivateProfileString(section, null, null, this.FilePath);
	}
	public bool Exists()
	{
		return System.IO.File.Exists(this.FilePath);
	}
}



评论

暂无评论