在开发的过程中,很多时候我们需要用到配置文件,根据个人喜好或者开发需求,我们经常会把配置信息写到文本或者xml文件里面。在桌面程序开发中,便于调试,安装人员的操作方便,一般把配置写到文本里面,对于 Web 程序,一般把配置写到XML文件里面,下面是我实现的方法:
从文本里面读配置
在类文件 GlobalVariabletxt 中
static GlobalVariabletxt()
{
try
{
string strFilePath = Application.StartupPath;
if ( strFilePath.EndsWith("\\") )
{
strFilePath += "SysConfig.txt";
}
else
{
strFilePath += http://www.cnblogs.com/jxhsun/admin/file://\\SysConfig.txt;
}
StreamReader sreadSys = null;
try
{
//读取配置文件数据库配置值:服务器,用户名,密码,数据库名称
FileStream streamRead = new FileStream( strFilePath, FileMode.Open, FileAccess.Read );
sreadSys = new StreamReader( streamRead, Encoding.Default );
string strLine = sreadSys.ReadLine();
string[] arrLines = strLine.Split(',');
gServerName = arrLines[0];
gUserName = arrLines[1];
gPassword = arrLines[2];
gDataSource = arrLines[3];
gViewTimeDir = arrLines[4];
}
catch//出错则写入默认值
{
}
finally
{
if ( sreadSys != null )
{
sreadSys.Close();
}
}
}
catch
{
}
}
在使用的窗口页面
string strServerName = this.txtServer.Text.Trim();
string strDataSource = this.txtDataSource.Text.Trim();
string strPassword = this.txtPassword.Text.Trim();
string strUserName = this.txtUserName.Text.Trim();
string strviewtime = txtViewTime.Text.Trim();
GlobalVariable.gServerName = strServerName;
GlobalVariable.gDataSource = strDataSource;
GlobalVariable.gPassword = strPassword;
GlobalVariable.gUserName = strUserName;
GlobalVariable.gViewTimeDir = strviewtime;