C# 读写ini文件

1.添加引用

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

2.声明API函数

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

3.文件读取的方法

1     private string ContentValue(string Section, string key, string strFilePath)
2     {
3         StringBuilder temp = new StringBuilder(1024);
4         GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
5         return temp.ToString();
6     }

4.读取文件实例

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

效果图:

posted @ 2015-11-19 09:59  imstrive  阅读(1288)  评论(0编辑  收藏  举报