Perhaps an alternate approach, create a key under appSettings.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="file_location" value="C:\users\test\desktop\file_location.csv"/>
</appSettings>
</configuration>
Add the following class to your project which has a get and set for file_location
.
using System;
using System.Configuration;
using System.IO;
using static System.Configuration.ConfigurationManager;
namespace YourNamespace
{
public class ApplicationSettings
{
public static void SetFileLocation(string fileName) => SetValue("file_location", fileName);
public static string GetFileLocation => AppSettings["file_location"];
public static void SetValue(string key, string value)
{
var appName = Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
var configFile = Path.Combine(appName,
$"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.exe.config");
var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
var config = OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
throw new Exception($"Key {key} does not exist");
}
config.AppSettings.Settings[key].Value = value;
config.Save();
RefreshSection("appSettings");
}
}
}
Console app test
namespace YourNamespace
{
class Program
{
static void Main(string[] args)
{
var current = ApplicationSettings.GetFileLocation;
Console.WriteLine($"Current path: {current}");
ApplicationSettings.SetFileLocation(current == "C:\\users\\test\\desktop\\file.csv" ?
"C:\\users\\test\\desktop\\file_location.csv" :
"C:\\users\\test\\desktop\\file.csv");
Console.WriteLine($"Current path after set: {ApplicationSettings.GetFileLocation}");
Console.ReadLine();
}
}
}
In regards to updating, see the following