Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change app.config at install time

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.

like image 400
user95542 Avatar asked Apr 24 '09 15:04

user95542


2 Answers

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

like image 106
Aaron Daniels Avatar answered Oct 23 '22 11:10

Aaron Daniels


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();
        }
    }
}
like image 5
Chris Doggett Avatar answered Oct 23 '22 10:10

Chris Doggett