Storing values in the App.config file will allow others to update values without needing to access the source code and rebuilding the project. For example, when delivering a solution to another team which may need to change variables such as url, username or emails, then building the project with this in mind and retrieving values from App.config will allow them to easily make those changes.
- Add references and using statements to System.Configuration
- Add a key value pair to App.config
- Get the value with ConfigurationManager.AppSettings
- Edit the key value pair from the XML file MyApp.exe.config
On editing the config file, there will be no need to recompile the executable, but the values will be updated.
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="Username" value="Hoopy"/> <add key="Environment" value="Testing"/> </appSettings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> </configuration> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Configuration; namespace StoreValues { class Program { static void Main(string[] args) { string user = ConfigurationManager.AppSettings["Username"]; string env = ConfigurationManager.AppSettings["Environment"]; Console.WriteLine("Hello, " + user + "."); Console.WriteLine("Welcome to the " + env + " Environment."); Console.ReadLine(); } } } |
1 2 3 |
Hello, HoopyTest. Welcome to the Testing Environment. > |
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="Username" value="HoopyProd"/> <add key="Environment" value="Production"/> </appSettings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> </configuration> |
1 2 3 |
Hello, HoopyProd. Welcome to the Production Environment. > |