Search notes:
C-Sharp: read settings from an App.exe.config file
//
// csc App.cs
using System;
using System.Configuration;
namespace TQ84 {
class App {
static void Main(string[] args) {
//
// Read App.exe.config
//
System.Collections.Specialized.NameValueCollection settings = ConfigurationManager.AppSettings;
//
// Get specific values:
//
Console.WriteLine("num = " + settings["num"] ?? "n/a");
Console.WriteLine("txt = " + settings["txt"] ?? "n/a");
Console.WriteLine("bla = " + settings["bla"] ?? "n/a");
//
// Iterate over all values
//
Console.WriteLine("--------------");
Console.WriteLine("There are {0} setting(s) in App.exe.config:", settings.Count);
foreach (var key in settings.AllKeys) {
Console.WriteLine(" {0} = {1}", key, settings[key]);
}
}
}
}
Sample config file
The config file must be named app-name.exe.config
, for this example App.exe.config
:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime
version="v4.0"
sku =".NETFramework,Version=v4.5"
/>
</startup>
<appSettings>
<add key="num" value="42" />
<add key="txt" value="Hello World" />
</appSettings>
</configuration>
Creating and running executable
We use the C-Sharp compiler
csc.exe
to turn the source code
App.cs
into an
executable.
If there is also an App.exe.config
file, we remove it:
rm App.exe -errorAction ignore
rm App.exe.config -errorAction ignore
csc -nologo App.cs
Running the exe with …
mv App.exe.config.github App.exe.config
write-host -foreGroundColor green 'execute app with App.exe.config'
& .\App
… and without the config file:
mv App.exe.config.github App.exe.config
write-host -foreGroundColor green 'execute app with App.exe.config'
& .\App