CSharp C# - App.Config – Example of programmic change
Programmically change an App.Config file:
Note that this only changes in memory - I do not see any changes to the App.Config file.
To see an example where the file is actually modified go here.
To see an example where the file is actually modified go here.
TOC
Program.cs
Output
App.Config
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration; //Requires System.Configuration.dll
namespace TestAppConfigMod
{
class Program
{
static void Main(string[] args)
{
string keyNow = "Browser";
string valueNow = "Mozilla";
/*
* OUTPUT from the above:
* The App.Settings key "Browser" is now "Mozilla"
* Press enter to complete program.
*/
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (ConfigurationManager.AppSettings[keyNow] == null)
{
config.AppSettings.Settings.Add(keyNow, valueNow);
}
else
{
config.AppSettings.Settings[keyNow].Value = valueNow;
}
config.Save();
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine("The App.Settings key \"{0}\" is now \"{1}\"", keyNow, ConfigurationManager.AppSettings[keyNow]);
Console.WriteLine("Press enter to complete program.");
Console.ReadLine();
}
}
}
App.Config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key ="Browser" value="IE"/>
<add key="myURL" value="https://mydomainA.com/" />
<add key="CompanyName" value="TestCompanyA"/>
</appSettings>
</configuration>
No comments:
Post a Comment