详情介绍:http://zh.wikipedia.org/wiki/INI%E6%96%87%E4%BB%B6
示例:
下面是一个虚拟的程序,其INI文件有两个小节,前面的小节是用来设置拥有者的信息,而后面的小节是用来设置数据库的位置。前面的注解记载谁最后编辑此文件,而后面的注解记录为何不使用域名而是使用IP地址。
[owner]
name=John Doe
organization=Acme Products [database]
server=192.0.2.42 ; use IP address in case network name resolution is not working
port=143
file = "acme payroll.dat"
IniHelper 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; namespace SingleStore.Code
{
public class IniHelper
{ // 声明INI文件的写操作函数 WritePrivateProfileString()
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); // 声明INI文件的读操作函数 GetPrivateProfileString()
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath); //获取ini文件的路径
private string sPath = null;
public IniHelper(string path)
{
this.sPath = path;
} /// <summary>
/// 写入INI文件
/// </summary>
/// <param name="section">配置节</param>
/// <param name="key">键名</param>
/// <param name="value">键值</param>
public void WriteValue(string section, string key, string value)
{
// section=配置节,key=键名,value=键值,path=路径
WritePrivateProfileString(section, key, value, sPath);
} /// <summary>
/// 读取INI文件配置节下的键
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <returns></returns>
public string ReadValue(string section, string key)
{
// 每次从ini中读取多少字节
StringBuilder temp = new StringBuilder();
// section=配置节,key=键名,temp=上面,path=路径
GetPrivateProfileString(section,key,"",temp,,sPath);
return temp.ToString();
}
}
}
Form窗体调用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SingleStore.Code; namespace SingleStore
{
public partial class Login : Form
{
public Login()
{
InitializeComponent(); string IniPath = Directory.GetCurrentDirectory(); //写入ini
IniHelper ini = new IniHelper(IniPath + "/config.ini");
ini.WriteValue("StoreShop", "userName", "admin");
ini.WriteValue("StoreShop", "pwd", "admin");
ini.WriteValue("StoreShop", "isRePwd", ""); //读取ini
string ispwd = ini.ReadValue("StoreShop", "isRePwd");
string xis = "";
if (ispwd == "")
{
xis = "是";
}
else
{
xis = "否";
}
MessageBox.Show("用户名:" + ini.ReadValue("StoreShop", "userName") + "\n" +
"密码:" + ini.ReadValue("StoreShop", "pwd") + "\n" +
"是否记住密码:" + xis);
}
}
}