C# 读写ini文件

时间:2023-03-08 23:04:12
C# 读写ini文件

1.添加引用

using System.IO;
using System.Runtime.InteropServices;

2.声明API函数

     #region  API函数声明
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
[DllImport("kernel32")]
private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filepath);
#endregion

3.文件读取的方法

     private string ContentValue(string Section, string key, string strFilePath)
{
StringBuilder temp = new StringBuilder();
GetPrivateProfileString(Section, key, "", temp, , strFilePath);
return temp.ToString();
}

4.读取文件实例

         private void button1_Click(object sender, EventArgs e)
{
string path = Application.StartupPath + @"\配置文件.ini";
textBox1.Text = ContentValue("Server", "path", path);
textBox2.Text = ContentValue("Server", "cmd", path);
textBox3.Text = ContentValue("Client", "path", path);
textBox4.Text = ContentValue("Client", "cmd", path);
}

效果图:

C# 读写ini文件