Created
December 26, 2021 07:59
-
-
Save ruyut/8957da21ec415f33cd9057057651ad0e to your computer and use it in GitHub Desktop.
C# ConfigurationManager example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Configuration; | |
namespace RuyutConsoleApp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("WriteSettings"); | |
WriteSettings("k1", "t1"); | |
Console.WriteLine("ReadSettings"); | |
ReadSettings("k1"); | |
Console.WriteLine("ReadAllSettings:"); | |
ReadAllSettings(); | |
} | |
private static void WriteSettings(string key, string value) | |
{ | |
try | |
{ | |
var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); | |
var settings = configuration.AppSettings.Settings; | |
if (settings[key] == null) | |
{ | |
settings.Add(key, value); | |
} | |
else | |
{ | |
settings[key].Value = value; | |
} | |
configuration.Save(ConfigurationSaveMode.Minimal); | |
ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine("WriteSettings " + e); | |
} | |
} | |
private static void ReadSettings(string key) | |
{ | |
try | |
{ | |
var appSettings = ConfigurationManager.AppSettings; | |
string result = appSettings[key] ?? "Not found"; | |
Console.WriteLine(result); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine("ReadSettings " + e); | |
} | |
} | |
private static void ReadAllSettings() | |
{ | |
try | |
{ | |
var appSettings = ConfigurationManager.AppSettings; | |
if (appSettings.Count == 0) | |
{ | |
Console.WriteLine("AppSettings is empty."); | |
} | |
else | |
{ | |
foreach (var key in appSettings.AllKeys) | |
{ | |
Console.WriteLine("key: {0}, Value: {1}", key, appSettings[key]); | |
} | |
} | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment