views:

1627

answers:

3

How can I dynamically change a connectionString in the app.config file?

I have an application written with windows forms, c# 3.0 and Linq to Sql. I need to change the connection string when i install the application. How i do this?

When the user installs the program it must show a form with an option to change the connection string if exists or add one if it doesn't.

A: 

Check out this question. It has what you need to change values in the app.config dynamically through code.

Dillie-O
I was looking at an old version of the question. Using the link I provided, you can have a popup screen the first time the application is started to prompt the user to change things.
Dillie-O
+2  A: 

Write a secondary config file with an appSettings block using the settings from the installer. In your main config file, use the file attribute in appSettings to reference the second config file, like so:

<appSettings file="User.config">

Settings in the secondary config will override any matching keys in the main config.

In your installer:

public override void Install(IDictionary stateSaver)
{
    base.Install(stateSaver);

    string server = Context.Parameters["Server"];
    string port = Context.Parameters["Port"];
    string targetDir = Context.Parameters["TargetDir"];
    // Build your connection string from user-input parameters and add them to dictionary

    WriteAppConfig(targetDir, server, port);
}

private void WriteAppConfig(string targetDir, string server, string port)
{
    string configFilePath = Path.Combine(targetDir, "User.config");

    IDictionary<string, string> userConfiguration = new Dictionary<string, string>();

    userConfiguration["Server"] = server;
    userConfiguration["Port"] = port;

    ConfigGenerator.WriteExternalAppConfig(configFilePath, userConfiguration);
}

public class ConfigGenerator
{
    public static void WriteExternalAppConfig(string configFilePath, IDictionary<string, string> userConfiguration)
    {
        using (XmlTextWriter xw = new XmlTextWriter(configFilePath, Encoding.UTF8))
        {
            xw.Formatting = Formatting.Indented;
            xw.Indentation = 4;
            xw.WriteStartDocument();
            xw.WriteStartElement("appSettings");

            foreach (KeyValuePair<string, string> pair in userConfiguration)
            {
                xw.WriteStartElement("add");
                xw.WriteAttributeString("key", pair.Key);
                xw.WriteAttributeString("value", pair.Value);
                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            xw.WriteEndDocument();
        }
    }
}
Chris Doggett
+4  A: 

If you are using a .NET deployment project, can achieve this by using Custom Actions.

Aaron Daniels