我的做法是这样:
1、在项目ABC的下面建目录Settings,里面有文件Settings.xml,其内容是:
<?xml version="1.0" encoding="utf-8" ?>
<Section Name="Settings">
<Key Name="SQLServer" Value="mySvr" />
<Key Name="SQLDatabase" Value="myDb" />
<Key Name="SQLUID" Value="myId" />
<Key Name="SQLPWD" Value="myPw" />
</Section>
当然,这里就是数据库连结的基本信息。
2、在项目的web.config中,加入:
<configuration>
.....
<appSettings>
<add key="SettingsFile" value=". ettings ettings.XML"></add>
</appSettings>
</configuration>
3、在Global.asax.cs中:
protected void Application_Start(Object sender, EventArgs e)
{
SetConnectionString();
}
private void SetConnectionString()
{
String sServer, sDB, sUID, sPWD, strSettingsFile;
strSettingsFile = System.Web.HttpContext.Current.Server.MapPath("\\ABC\\") + System.Configuration.ConfigurationSettings.AppSettings["SettingsFile"];
Application["DatabaseConnectionString"] = "";
try
{
sServer = clsCommon.ReadSettings(strSettingsFile, "SQLServer");
sDB = clsCommon.ReadSettings(strSettingsFile, "SQLDatabase");
sUID = clsCommon.ReadSettings(strSettingsFile, "SQLUID");
sPWD = clsCommon.ReadSettings(strSettingsFile, "SQLPWD");
Application["DatabaseConnectionString"] = "Server=" + sServer.Trim() + ";Database=" + sDB.Trim() + ";uid=" + sUID.Trim() + ";pwd=" + sPWD.Trim() + ";";
}
catch(Exception excp)
{
throw(excp);
}
}
这里,从web.config中读到Setting.xml所在的相对路径,然后找到服务器上的文件,再读取其内容,就设定了Application级别的变量DatabaseConnectionString,当然,如果是要求各个session的连接字符串不一定相同,可以改成Session级别的。
4、在第3步中,用到的读取xml文件的函数实现如下:
using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
namespace ABC
{
/// <summary>
/// Summary description for clsCommon.
/// </summary>
public class clsCommon: ABC
{
private const String NOTFOUND = "<<nothing>>";
public clsCommon()
{
//
// TODO: Add constructor logic here
//
}
static public String ReadSettings(String strSettingsFile , String sKey)
{
XmlTextReader xmlTR = new XmlTextReader(strSettingsFile);
XmlDocument m_xmlDocument = new XmlDocument();
m_xmlDocument.Load(xmlTR);
xmlTR.Close();
String strResult;
strResult = GetSettingStr(m_xmlDocument, "Settings", sKey, "");
return strResult;
}
static public String GetSettingStr( XmlDocument xmlDocument , String SectionName , String KeyName, String DefaultValue )
{
String sKeyValue ;
sKeyValue = _GetSetting(xmlDocument, SectionName, KeyName);
if (sKeyValue == NOTFOUND )
sKeyValue = DefaultValue;
return sKeyValue;
}
static public String _GetSetting(XmlDocument xmlDocument ,String SectionName ,String KeyName )
{
String sKeyValue;
XmlNode xnSection;
XmlNode xnKey ;
xnSection = xmlDocument.SelectSingleNode("//Section[@Name='" + SectionName + "']");
if(xnSection == null )
sKeyValue = NOTFOUND;
else
{
xnKey = xnSection.SelectSingleNode ("descendant::Key[@Name='" + KeyName + "']");
if( xnKey == null )