一、读取
以下是ini文件内容
Server=.
DataBase=Ykt_Info
User Id=sa
PassWord=sa
Persist Security Info=True
下面函数读取ini文件内容,构造数据库串。构造目标为"Server=.;DataBase=Ykt_Info;User Id=sa;PassWord=sa;Persisit Security Info=True;"
数据库连接串SqlConnection sqlconn = new SqlConnection(IniReadValue());
private string IniReadValue()
{
try
{
using (StreamReader sr = new StreamReader("Data.ini", Encoding.GetEncoding("gb2312")))//利用using自动释放资源
{
if (sr.Peek() >= 0)
{
string Server=sr.ReadLine();
string DataBase=sr.ReadLine();
string User=sr.ReadLine();
string Pass=sr.ReadLine();
string PSI=sr.ReadLine();
}
sr.Close();
}
return Server+";"+DataBase+";"+User+";"+Pass+";"+PSI+";";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
二、写Ini
private void IniWriteValue()
{
try
{
string Server="Server="+ServerTextBox.text+";";
string DataBase="DataBase="+DataBaseTextBox.text+";";
string User="User Id="+UserTextBox.text+";";
string Pass="PassWord="+PassTextBox.text+";";
string PSI="Persisit Security Info="+PSITextBox.text+";";
using( StreamWriter sw = new StreamWriter("Data.ini", false, Encoding.GetEncoding("gb2312")))
{
sw.Flush();
sw.WriteLine(Server);
sw.WriteLine(DataBase);
sw.WriteLine(User);
sw.WriteLine(Pass);
sw.WriteLine(PSI);
sw.Close();
}
MessageBox.Show("数据库配置成功!");
}
catch (Exception ex)
{
MessageBox.Show("配置文件路径不对,无法写入!"+ex.Message.ToString());
}
}
本文中读取已经验证过,写入未验证。目前项目中使用这种方法进行读写ini,不知道有没有再好一点的方法。