Sie sind auf Seite 1von 4

http://www.aspsnippets.com/Articles/Programmatically-Add-or-Update-Connection-Stringin-ASPNet-WebConfig-File.aspx Namespaces You will need to inherit the following namespaces. C# using System.Xml; using System.Data.SqlClient; VB.

Net Imports System.Xml Imports System.Data.SqlClient Code snippet to add or update Connection String in Web.Config file The following method adds or updates the connection string based on the connection string name. If the connection string with the name does not exists a new connection string node will be created in the Web.Config file. C# private void AddUpdateConnectionString(string name) { bool isNew = false; string path = Server.MapPath("~/Web.Config"); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name)); XmlNode node; isNew = list.Count == 0; if (isNew) { node = doc.CreateNode(XmlNodeType.Element, "add", null); XmlAttribute attribute = doc.CreateAttribute("name"); attribute.Value = name; node.Attributes.Append(attribute); attribute = doc.CreateAttribute("connectionString"); attribute.Value = ""; node.Attributes.Append(attribute); attribute = doc.CreateAttribute("providerName"); attribute.Value = "System.Data.SqlClient"; node.Attributes.Append(attribute); } else { node = list[0]; } string conString = node.Attributes["connectionString"].Value; SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString); conStringBuilder.InitialCatalog = "TestDB"; conStringBuilder.DataSource = "myserver"; conStringBuilder.IntegratedSecurity = false; conStringBuilder.UserID = "test"; conStringBuilder.Password = "12345";

node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString; if (isNew) { doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node); } doc.Save(path); } VB.Net Private Sub AddUpdateConnectionString(name As String) Dim isNew As Boolean = False Dim path As String = Server.MapPath("~/Web.Config") Dim doc As New XmlDocument() doc.Load(path) Dim list As XmlNodeList = doc.DocumentElement.SelectNodes(String.Format("connectionStrings/add[@name='{0}']", name)) Dim node As XmlNode isNew = list.Count = 0 If isNew Then node = doc.CreateNode(XmlNodeType.Element, "add", Nothing) Dim attribute As XmlAttribute = doc.CreateAttribute("name") attribute.Value = name node.Attributes.Append(attribute) attribute = doc.CreateAttribute("connectionString") attribute.Value = "" node.Attributes.Append(attribute) attribute = doc.CreateAttribute("providerName") attribute.Value = "System.Data.SqlClient" node.Attributes.Append(attribute) Else node = list(0) End If Dim conString As String = node.Attributes("connectionString").Value Dim conStringBuilder As New SqlConnectionStringBuilder(conString) conStringBuilder.InitialCatalog = "TestDB" conStringBuilder.DataSource = "myserver" conStringBuilder.IntegratedSecurity = False conStringBuilder.UserID = "test" conStringBuilder.Password = "12345" node.Attributes("connectionString").Value = conStringBuilder.ConnectionString If isNew Then doc.DocumentElement.SelectNodes("connectionStrings")(0).AppendChild(node) End If doc.Save(path) End Sub Downloads You can download the complete source code in VB.Net and C# using the download link provided below. UpdateConnectionStringsWebConfig.zip

http://forums.asp.net/post/2994438.aspx Best method for changing a web.config connectionstring at runtime? Mar 09, 2009 10:32 PM|LINK The connection string in the web.config are not exactly meant to be handled this way. However you could write a class to do this for you. Lets say we want pieces of the connection strings, i have never thought about doing it this way but i guess it makes sense. Although you would have 1 connection string that is for users not logged in that only gets used for your login so lets set that up first <connectionStrings> <add name="Login_SQL" connectionString="Data Source=.\{servername};User ID={logincontroluser};Password={logincontrolpass};persist security info=False;initial catalog={database};" providerName="System.Data.SqlClient"/> </connectionStrings> So the above only gets used for the login control. Next we will add a few more items to the web.config directly below the connectionStrings <appSettings> <add key="DataSource" value="Data Source=.\;"/> <add key="InitCatalog" value="initial catalog={databasename};"/> </appSettings> Now for the final piece of putting it together in an easy to use, and easy to maintain method. using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; /// &lt;summary&gt; /// Summary description for DB_String /// </summary> public class DB_String { public string ConnectionString { get { //Put your own method to retrieve the username and password below instead of my examples string username = "test"; string password = "test"; //Build the connection string from the AppSettings Pieces. string conString = string.Format("{0};User ID={1};Password={2};{3}", ConfigurationManager.AppSettings["DataSource"].ToString(), username, password,

ConfigurationManager.AppSettings["InitCatalog"].ToString()); return conString; } } } What we did before is just referenced the two pieces from the Web.config which contains the most important values of the Database engine and the intial cataloge. Now you will have to add your own methods to caputre the username and password Then you can call this class anywhere in your project by using ConnectionString="<%= new DB_String().ConnectionString %>" string Connectionstring = new DB_String().ConnectionString ; Good luck

Das könnte Ihnen auch gefallen