App Settings for a .NET Console App: Save, Retrieve and Validate IPAddress and Port
coding dnet csharp console appsettings ipaddress port
Store, retrieve and update settings for a C# Console app that communicates with a remote Arduino IP Service.
Microsoft Learn
Link: ConfigurationManager.AppSettings Property
About
A static class SettingsManager
was created with methods to store, retrieve and update the Console applications settings, IPAddress and Port. Both settings were stored as a string and validated upon retrieval. The string version of the IPAddress is though used in-app as a string, whereas as part of the Port value verification, it is parsed into an an integer in which form it is used in-app.
App.config file
Some documentation (including the above link) says that an App.config file defining the settings is required in the code as a resource. But it is ignored. A config file is created in the runtime folder at runtime. It is called <AssemblyName>.dll.config.
For example, when a .NET Console app named SoftataConsole
was run from Visual Studio in Debug mode, the file SoftataConsole.dll.config
was generated in <App Containing Folder>\SoftataConsole\bin\Debug\net8.0
:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="IpaddressStr" value="2" />
<add key="Port" value="3" />
</appSettings>
</configuration>
SettingsManager Class Methods
//Only sets them to null
static void ClearAllSettings();
// Nb: To completely delete them, just delete the config file from the runtime folder.
//Adds new key value pair or updates
static void AddUpdateAppSettings(string key, string value);
//Iterate through all key value pairs
static void ReadAllSettings();
//Get value for key if it exists
static string ReadSetting(string key);
AppSettingsManager.cs File
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftataConsole
{
internal static class SettingsManager
{
internal 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 (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
internal static void ClearAllSettings()
{
try
{
var appSettings = ConfigurationManager.AppSettings;
if (appSettings.Count == 0)
{
Console.WriteLine("ClearAll:AppSettings is empty.");
}
else
{
foreach (var key in appSettings.AllKeys)
{
Console.WriteLine("ClearAll:Key: {0} Value: {1}", key, appSettings[key]);
appSettings[key] = null;
}
}
}
catch (ConfigurationErrorsException ex)
{
Console.WriteLine("ClearAll:Error reading app settings");
Console.WriteLine(ex.Message);
}
}
internal static string ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "";
return result;
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
return "";
}
}
internal static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
}
}
Retrieving the IPAddress from the Console code
//Default setting
string IPAddress = "192.168.0.12";
//SettingsManager.ClearAllSettings();
SettingsManager.ReadAllSettings();
//Not required
//Read setting from app settings if it exists and validate
string _ipaddressStr = SettingsManager.ReadSetting("IpaddressStr");
if (!string.IsNullOrEmpty(_ipaddressStr))
{
if (_ipaddressStr.Count(c => c == '.') == 3)
{
if (IPAddress.TryParse(_ipaddressStr, out IPAddress? address))
{
Ipaddress = _ipaddressStr;
}
else
Console.WriteLine("\t\tInvalid App Settings IP Address");
}
else
Console.WriteLine("\t\tInvalid App Settings IP Address");
}
else
{
// Add default setting to app settings
SettingsManager.AddUpdateAppSettings("IpaddressStr", ipaddressStr);
}
Retrieving the Port from the Console code.
//Default setting:
in port = 4242;
string _port = SettingsManager.ReadSetting("Port");
if (!string.IsNullOrEmpty(_port)
{
if(int.TryParse(_port, out int _portNo))
{
port = _portNo;
}
else
Console.WriteLine("\t\tInvalid AppSettings Port");
}
else
{
SettingsManager.AddUpdateAppSettings("Port", port.ToString());
}
Example Run
Key: IpaddressStr Value: 192.168.0.12
Key: Port Value: 4242
Softata Tests
Default Softata Server is at 192.168.0.12:4242
Enter new values or press [Enter] to continue:
Plz Enter IPAdress:
Plz Enter Port:
Selected Softata Server is at 192.168.0.12:4242
Topic | Subtopic | |
< Prev: | Softata | Added Actuator Class - Relay |
This Category Links | ||
Category: | Coding Index: | Coding |
Next: > | C++ Coding | const char * data type |
< Prev: | Nuget updates | With errors such as NU1605 and NU1301 |