App.Config Change Value

App.Config change value

You cannot use AppSettings static object for this. Try this

string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

config.AppSettings.Settings["YourThing"].Value = "New Value";
config.Save();

How to update app settings key value pair dynamically on app.config file in c# winforms


Configuration configuration = ConfigurationManager.
OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
configuration.AppSettings.Settings["logPath"].Value = DateTime.Now.ToString("yyyy-MM-dd");
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");

Set value in app.config - no write access to Program Files

You can use the User settings capability of the application settings api for this. These settings are stored in %userprofile%\appdata\local or %userprofile%\Local Settings\Application Data (windows version dependent).

User settings has some limitations: it is, as it says, user specific not global for all users - but presumably if you are updating values at runtime then that's what you want, otherwise you need something like this.

You essentially just have to add a .settings file, which creates the applicationSettings and/or userSettings sections in your app.config (see MSDN: How To: Create a New Setting at Design Time), create your property and set it to User, not Application, and then do this at runtime:

Properties.Settings.Default.myColor = Color.AliceBlue;
Properties.Settings.Default.Save();

The .settings property will create a user settings entry in your app.config that looks like this:

<setting name="Setting1" serializeAs="String" >
<value>My Setting Value</value>
</setting>

You can use this to set the default value that a user session will get before any user-specific value has been saved.

Reference: MSDN: Using Application Settings and User Settings

Change value in app.config within TeamCity

There are a couple of approaches to this.

Just choose one of the following scripts, add it to your source control and setup a PowerShell build runner in your build configuration to run the script passing in the required parameters, before you run the NUnit step. If you choose option two then you'll also need to consider the transform dll.

AppSettingReplace.ps1

If you only want to change a single value you can achieve this with some simple PowerShell that will load up the config file into an xml document, iterate the app settings and change the one that matches.

# -----------------------------------------------
# Config Transform
# -----------------------------------------------
#
# Ver Who When What
# 1.0 Evolve Software Ltd 13-05-16 Initial Version

# Script Input Parameters
param (
[ValidateNotNullOrEmpty()]
[string] $ConfigurationFile = $(throw "-ConfigurationFile is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $ApplicationSetting = $(throw "-ApplicationSetting is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $ApplicationSettingValue = $(throw "-ApplicationSettingValue is mandatory, please provide a value.")
)

function Main()
{
$CurrentScriptVersion = "1.0"

Write-Host "================== Config Transform - Version"$CurrentScriptVersion": START =================="

# Log input variables passed in
Log-Variables
Write-Host

try {
$xml = [xml](get-content($ConfigurationFile))
$conf = $xml.configuration
$conf.appSettings.add | foreach { if ($_.key -eq $ApplicationSetting) { $_.value = $ApplicationSettingValue } }
$xml.Save($ConfigurationFile)
}
catch [System.Exception] {
Write-Output $_
Exit 1
}

Write-Host "================== Config Transform - Version"$CurrentScriptVersion": END =================="
}

function Log-Variables
{
Write-Host "ConfigurationFile: " $ConfigurationFile
Write-Host "ApplicationSetting: " $ApplicationSetting
Write-Host "ApplicationSettingValue: " $ApplicationSettingValue
Write-Host "Computername:" (gc env:computername)
}

Main

Usage

AppSettingReplace.ps1 "D:\MyPath\app.config" "BaseTestDataPath" "%teamcity.build.workingDir%"


XdtConfigTransform.ps1

The alternative approach to this is to provide full config transformation support using XDT - This does require Microsoft.Web.XmlTransform.dll to end up on the server somehow (which I normally put into source control).

The following script will transform one config file with another one.

# -----------------------------------------------
# Xdt Config Transform
# -----------------------------------------------
#
# Ver Who When What
# 1.0 Evolve Software Ltd 14-05-16 Initial Version

# Script Input Parameters
param (
[ValidateNotNullOrEmpty()]
[string] $ConfigurationFile = $(throw "-ConfigurationFile is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $TransformFile = $(throw "-TransformFile is mandatory, please provide a value."),
[ValidateNotNullOrEmpty()]
[string] $LibraryPath = $(throw "-LibraryPath is mandatory, please provide a value.")
)

function Main()
{
$CurrentScriptVersion = "1.0"

Write-Host "================== Xdt Config Transform - Version"$CurrentScriptVersion": START =================="

# Log input variables passed in
Log-Variables
Write-Host

if (!$ConfigurationFile -or !(Test-Path -path $ConfigurationFile -PathType Leaf)) {
throw "File not found. $ConfigurationFile";
Exit 1
}
if (!$TransformFile -or !(Test-Path -path $TransformFile -PathType Leaf)) {
throw "File not found. $TransformFile";
Exit 1
}

try {

Add-Type -LiteralPath "$LibraryPath\Microsoft.Web.XmlTransform.dll"
$xml = New-Object Microsoft.Web.XmlTransform.XmlTransformableDocument;
$xml.PreserveWhitespace = $true
$xml.Load($ConfigurationFile);

$xmlTransform = New-Object Microsoft.Web.XmlTransform.XmlTransformation($TransformFile);
if ($xmlTransform.Apply($xml) -eq $false)
{
throw "Transformation failed."
}
$xml.Save($ConfigurationFile)
}
catch [System.Exception] {
Write-Output $_
Exit 1
}

Write-Host "================== Xdt Config Transform - Version"$CurrentScriptVersion": END =================="
}

function Log-Variables
{
Write-Host "ConfigurationFile: " $ConfigurationFile
Write-Host "TransformFile: " $TransformFile
Write-Host "LibraryPath: " $LibraryPath
Write-Host "Computername:" (gc env:computername)
}

Main

Usage

XdtConfigTransform.ps1 "D:\MyPath\app.config" "D:\MyPath\app.transform.config" "%teamcity.build.workingDir%\Library"

Note: The last parameter is the path to the directory that contains Microsoft.Web.XmlTransform.dll

Github Repository - teamcity-config-transform

Hope this helps

How to update an value in app.config file?

This code should work:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["IP"].Value = "10.0.0.2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

How can I change the value of a custom configSections variable?

You have an option to load the config into XML, edit the node value and save it back. Give a try with this

        var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

xmlDoc.SelectSingleNode("//serverConfiguration").Attributes["serverUrl"].Value = "http://staging/server/";
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

Probably, it is a good idea to refresh the Config sections after file is saved.

ConfigurationManager.RefreshSection

ConfigurationManager.AppSettings - How to modify and save?

Perhaps you should look at adding a Settings File. (e.g. App.Settings)
Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.



Related Topics



Leave a reply



Submit