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.
If you are using a .NET deployment project, can achieve this by using Custom Actions.
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With