本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。把下面的代码改动一下,就可以在你的程序中使用,当然
别忘记加上名字空间哦。
using system;
using system.io;
using system.runtime.interopservices;
using system.text;
namespace sx_mdi
{
/// <summary>
/// summary description for class1.
/// </summary>
public class inifile
{
//文件ini名称
public string path;
////声明读写ini文件的api函数
[dllimport("kernel32")]
private static extern long writeprivateprofilestring(string section,string key,string val,string filepath);
[dllimport("kernel32")]
private static extern int getprivateprofilestring(string section,string key,string def,stringbuilder retval,int size,string filepath);
//类的构造函数,传递ini文件名
public inifile(string inipath)
{
//
// todo: add constructor logic here
//
path = inipath;
}
//写ini文件
public void iniwritevalue(string section,string key,string value)
{
writeprivateprofilestring(section,key,value,this.path);
}
//读取ini文件指定
public string inireadvalue(string section,string key)
{
stringbuilder temp = new stringbuilder(255);
int i = getprivateprofilestring(section,key,"",temp,255,this.path);
return temp.tostring();
}
}
}
操作范例:
public static sqlconnection myconnection()
{
string spath;
string servername,userid,spwd,dataname;
spath = getpath();
inifile ini = new inifile(spath);
servername = ini.inireadvalue ("database","server");
userid = ini.inireadvalue ("database","uid");
spwd = ini.inireadvalue ("database","pwd");
dataname = ini.inireadvalue ("database","database");
string strsql = "server =" + servername+";uid ="+ userid +";pwd =;database ="+ dataname;
sqlconnection myconn=new sqlconnection(strsql);
return myconn;
}