0

I have a scenario where i am getting dynamically generated databases. I want to create a connection string for each database. So only initial catalog parameter will be changing. Other parameters i ll get it from web config file. It is already having all entries of connection string. I want to change only initial catalog part dynamically based on database created.

Please suggest is there any way to easily to do this.

3 Answers 3

3

use the SqlConnectionStringBuilder class

SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(ConnectionStringFromConfig)
   { InitialCatalog = "your CatalogName" }; // you can add other parameters.

then use this connectionstring where required

conn.ConnectionString;
Sign up to request clarification or add additional context in comments.

Comments

2

Use SqlConnectionStringBuilder. Set it up from the config file and change the InitialCatalog for each database.

Comments

0

Try with this line of code, it will change the connection string in web config file as you want. I did this with TextBox,

 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}']", "conn"));
    XmlNode node;
    isNew = list.Count == 0;
    if (isNew)
    {
        node = doc.CreateNode(XmlNodeType.Element, "add", null);
        XmlAttribute attribute = doc.CreateAttribute("name");
        attribute.Value = "conn";
        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 = T1.Text;
    node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
    if (isNew)
    {
        doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
    }
    doc.Save(path);

This may be a hint for your hurdle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.