asp.net20 根据参数建立数据库,然后通过代码自动更改连接字符串.以下方法都不成功?
public void UpdateWebConfigForSqlProvider(string connectionString)
{
string webConfigFilePath = @"D:\MyProjectSample\Web.Config";
string connectionToken = "^SqlConnectionString^";
string webConfig; // Read the web.config file
//
StreamReader inputFile = new StreamReader(webConfigFilePath);
webConfig = inputFile.ReadToEnd();
inputFile.Close(); // Find the connection string section
//
int connectionTokenIndex = webConfig.IndexOf(connectionToken); if (connectionTokenIndex != -1)
{ // Exists, replace value
//
webConfig = webConfig.Replace(connectionToken, connectionString); } // All done, write the file back out
//
StreamWriter output = new StreamWriter(File.Open(webConfigFilePath, FileMode.Create));
output.Write(webConfig);
output.Flush();
output.Close(); }
private bool WriteWebConfig()
{
System.IO.FileInfo FileInfo = new System.IO.FileInfo(@"D:\MyProjectSample\Web.Config");
if (!FileInfo.Exists)
{
//throw new InstallException("Missing config file :" + this.Context.Parameters["targetdir"] + "/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"]["connectionStrings"])
{
if (Node.Name == "add")
{
if (Node.Attributes.GetNamedItem("name").Value == "MonitorConnectionString")
{
Node.Attributes.GetNamedItem("connectionString").Value = String.Format("Data Source={0};database={1};User ID={2};Password={3}", ".", "bankdb", "sa", "");
FoundIt = true;
}
}
}
if (!FoundIt)
{
throw new ApplicationException("Error when writing the config file: web.config");
}
xmlDocument.Save(FileInfo.FullName);
return FoundIt;
}
public void UpdateWebConfigForSqlProvider(string connectionString)
{
string webConfigFilePath = @"D:\MyProjectSample\Web.Config";
string connectionToken = "^SqlConnectionString^";
string webConfig; // Read the web.config file
//
StreamReader inputFile = new StreamReader(webConfigFilePath);
webConfig = inputFile.ReadToEnd();
inputFile.Close(); // Find the connection string section
//
int connectionTokenIndex = webConfig.IndexOf(connectionToken); if (connectionTokenIndex != -1)
{ // Exists, replace value
//
webConfig = webConfig.Replace(connectionToken, connectionString); } // All done, write the file back out
//
StreamWriter output = new StreamWriter(File.Open(webConfigFilePath, FileMode.Create));
output.Write(webConfig);
output.Flush();
output.Close(); }
private bool WriteWebConfig()
{
System.IO.FileInfo FileInfo = new System.IO.FileInfo(@"D:\MyProjectSample\Web.Config");
if (!FileInfo.Exists)
{
//throw new InstallException("Missing config file :" + this.Context.Parameters["targetdir"] + "/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"]["connectionStrings"])
{
if (Node.Name == "add")
{
if (Node.Attributes.GetNamedItem("name").Value == "MonitorConnectionString")
{
Node.Attributes.GetNamedItem("connectionString").Value = String.Format("Data Source={0};database={1};User ID={2};Password={3}", ".", "bankdb", "sa", "");
FoundIt = true;
}
}
}
if (!FoundIt)
{
throw new ApplicationException("Error when writing the config file: web.config");
}
xmlDocument.Save(FileInfo.FullName);
return FoundIt;
}
首先,先看看如果从web.config里提取appSettings里的配置值,示例代码如下:
key="pagetitle" value="Job Site Starter Kit (Ver.1.0)">
key="sitelogo" value="logo.gif">
key="advertiseemail" value="[email protected]"> 利用ASP.NET2.0提供的一组API函数,您可以很容易的获取AppSettingsSection里所有的Keys/value组对,如下: Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettings = (AppSettingsSection) config.GetSection("appSettings");
string[] appKeys = appSettings.Settings.AllKeys; for (int j = 0; j < appSettings.Settings.Count; j++)
{
//这里只进行简单的输出
Response.Write(appSettings.Settings[appKeys[j]].Value);
Response.Write("");
} 上面代码只是进行简单的输出所有Key的value值,然而,你可能想获取的仅仅是某一个key的值,这也非常简单,如下: Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
string pateTitle= appSettings.Settings["pagetitle"].Value; //获取key为patetitle的value值
string siteLogo= appSettings.Settings["siteLogo"].Value; //获取key为sitelogo的value值 对于数据库连接字符串,在ASP.NET2.0里提供了专门的配置节如下:
name="connectionstring"
connectionString="Data Source=SQLEXPRESS;AttachDbFilename=JsskDb.mdf; … .."/>
name="MyProviderConnectionString"
connectionString="Data Source=SQLEXPRESS;Integrated Security=True; … …"/> 这样我们很容易获取数据库连接字符串如下: Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionstring ");
ConnectionStringSettingsCollection conCollection = conSection.ConnectionStrings; foreach (ConnectionStringSettings conSetting in conCollection)
{
Response.Write(conSetting.ConnectionString);
Response.Write("");
} 另外,利用API函数,你同时还可以在代码里更改web.config数据库连接的配置的值,如下 Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
conSection.ConnectionStrings["SQLConnectionString"].ConnectionString = "Data Source=SQLEXPRESS;Integrated Security=True; … …";
config.Save(); 这里最有意思的可能就是类的转换,在里,使用的是AppSettingsSection类,在 connectionStrings>里使用的的是ConnectionStringsSection类,事实上,ASP.NET2.0提供的一组函数都是“配置节名+Section”的形式提供的类。 在ASP.NET官方网站曾经对此专门介绍,可以找不到该文件了。
在ASP.NET2.0里提供了两种方式对数据库连接字符串加密,一种是使用asp_regii命令,一种是通过代码,下面显示的是通过代码方式对数据库连接字符串加密,代码如下: Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configSection = config.GetSection("connectionStrings"); if (configSection.SectionInformation.IsProtected)
{
//如果已经加密,就不用再加密了
configSection.SectionInformation.UnprotectSection();
config.Save();
}
else
{
configSection.SectionInformation.ProtectSection ("DataProtectionConfigurationProvider");
config.Save();
} 修改appSettings中某个键值的方法: public static void writeConfig(string item, string key, string value)
{
if (item == "")
{
item = "appSettings";
}
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
AppSettingsSection appSection = (AppSettingsSection)config.GetSection(item);
if (appSection.Settings[key] == null)
{
appSection.Settings.Add(key, value);
config.Save();
}
else
{
appSection.Settings.Remove(key);
appSection.Settings.Add(key, value);
config.Save();
}
}
{
FileInfo fileinfo = new FileInfo(Context.Parameters["targetdir"] + "\\web.config");
if (!fileinfo.Exists)
{
throw new InstallException("没有找到配置文件");
}
XmlDocument xmldocument=new XmlDocument();
xmldocument.Load(fileinfo.FullName);
Boolean FoundIt = false;
foreach(XmlNode node in xmldocument.SelectSingleNode("appSettings").ChildNodes)
{
if (node.Name == "add")
{
if (node.Attributes.GetNamedItem("key").Value == "connString")
{
node.Attributes.GetNamedItem("value").Value= String.Format("Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1",Context.Parameters["server"],Context.Parameters["dbname"], Context.Parameters["user"], Context.Parameters["pwd"]);
FoundIt= true;
}
}
}
if (!FoundIt)
{
throw new InstallException("web.Config 文件没有包含connString连接字符串设置");
}
xmldocument.Save(fileinfo.FullName);
}
catch(Exception ex)
{
throw ex;
}
}
string virtualPath = "~";
2
3 try
4 {
5 Configuration config = WebConfigurationManager.OpenWebConfiguration(virtualPath);
6 AuthorizationSection authorizationSection = (AuthorizationSection)config.GetSection("system.web/authorization");
7 AuthorizationRuleCollection authorizationRuleCollection = authorizationSection.Rules;
8
9 foreach (AuthorizationRule authorizationRule in authorizationRuleCollection)
10 {
11 //相关操作
12
13 string roles = string.Empty;
14 foreach (string role in authorizationRule.Roles)
15 {
16 //相关操作
17 }
18 }
19
20 }
21 catch (Exception ex)
22 {
23 Label1.Text = ex.ToString();
24 }
25写配置文件
string configPath = "~";
2
3 Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
4 AuthorizationSection authorizationSection = (AuthorizationSection)config.GetSection("system.web/authorization");
5 AuthorizationRuleCollection authorizationRuleCollection = authorizationSection.Rules;
6 //相关操作
7
8 config.Save();