代码如下所示,这是一段来自ASP.NET网站部署的程序,
DataBaseName、ServerName、InStallAdmin、InstallPassword、dir
,这几个参数来自安装程序界面输入(具体怎样部署,请百度),这样就可以动态地改变网站连接配置文件的连接语句。。。
-
- /*先看一下我的web.config文件,要针对具体的情况具体地分析!!!为了简化说明,一些没必要的内容省略了。*/
- <?xml version="1.0"?>
- <configuration>
- ……
- <studynet>
- <connstr>user id=sa;pwd=;data source=(local);initial catalog=study;timeout=90</connstr>
- </studynet>
- ……
- <connectionStrings>
- <add name="ConnectionString" connectionString="Data Source=(local);Initial Catalog=study;User ID=sa;pwd=" providerName="System.Data.SqlClient"/>
- </connectionStrings>
- ……
- </configuration>
- /*通过观察以上代码发现,有两处连接内容需要修改的,分别位于configuration—studynet与configuration—connectionStrings,具体看代码,聪明的你一定会明白,在代码面前没有秘密!!!*/
- private bool WriteWebConfig()
- {
- string DBName = this.Context.Parameters["DataBaseName"];
- string DBServer = this.Context.Parameters["ServerName"];
- string DBUser = this.Context.Parameters["InStallAdmin"];
- string DBKey = this.Context.Parameters["InstallPassword"];
- System.IO.FileInfo FileInfo = new System.IO.FileInfo(this.Context.Parameters["dir"] + "/web.config");
- if (!FileInfo.Exists)
- {
- throw new InstallException("Missing config file :" + this.Context.Parameters["dir"] + "/web.config");
- }
- System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
- xmlDocument.Load(FileInfo.FullName);
- bool FoundIt = false;
- //对第一个连接修改
- foreach (System.Xml.XmlNode Node in xmlDocument["configuration"]["studynet"])
- {
- if (Node.Name == "connstr")
- {
- Node.InnerText = String.Format("Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};pwd={3}", DBServer, DBName, DBUser, DBKey);
- }
- }
- //对第二个连接修改
- foreach (System.Xml.XmlNode Node in xmlDocument["configuration"]["connectionStrings"])
- {
- if (Node.Name == "add")
- {
- if (Node.Attributes.GetNamedItem("name").Value == "ConnectionString")
- {
- Node.Attributes.GetNamedItem("connectionString").Value = String.Format("Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};pwd={3}", DBServer, DBName, DBUser, DBKey);
- FoundIt = true;
- }
- }
- }
- if (!FoundIt)
- {
- throw new InstallException("Error when writing the config file: web.config");
- }
- xmlDocument.Save(FileInfo.FullName);
- return FoundIt;
- }