Patan
Patan

Reputation: 17893

Replacing certain text in app.config at run time

I am writing a csharp console application. Depending on the user input I want to update my app.config file at run time.

Every time I need to replace a string with another string.

If the user has selected devenvironment, I need to replace all occurrence of testenvironment with devenvironement.

Please suggest how to do this at run time.

Upvotes: 0

Views: 2696

Answers (2)

SpiderCode
SpiderCode

Reputation: 10122

In General scenario it is not a good practice to change the configuration value at a runtime.

But still if it is requirement and there is not any other way to overcome the situation then you can update the App.Config file :

Below is the code sample of updating value of the AppSettings :

var config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
if (config.AppSettings == null || config.AppSettings.Settings == null)
{
    return;
}

config.AppSettings.Settings["Key"].Value = "My Value";
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);

Suggestion: Instead of above, I would suggest to create xml or text file and store it in AppData. And next time when you need it, you can get data from that file.

This shows how to write file in AppData folder.

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56727

You don't do that. Don't. Ever. Use user settings or come up with something of your own. User space applications are not allowed to write to the Program Files folder. Don't.

You can create a user setting that stores what kind of environment the user selected. Generalize all application settings so they contain a placeholder that covers the part you need to change between dev/test and replace that part in your code.

Example: Create a setting for a log file that should be environment specific. The value for this setting could be

"[Environment]\MyProgram\Logs"

Then, in your code you'd use someting like this to create the real path:

string logPath = Properties.Settings.Default.LogPath.Replace("[Environment]", IsDevEnvironment ? "C:\\DevEnvironment\\Test", "C:\\TestEnvironment");

Of course you'd fill in the real values here. Please note that they can also come from application- or user-settings.

Upvotes: 4

Related Questions