A
A
Anton Baryshev2021-03-25 22:58:36
WPF
Anton Baryshev, 2021-03-25 22:58:36

How to get information from a config file?

Hello! The application needs to get information from a configuration (.config) file. To do this, I use System.Configuration, and since I decided to split the configuration into several files for convenience, I created a static ApplicationConfiguration class. Using this class, you can get information from a specific configuration file:

// Contains objects of application configuration
    public static class ApplicationConfiguration
    {
        public static Configuration SettingsConfiguration { get; } = 
            ConfigurationManager.OpenMappedExeConfiguration(
                new ExeConfigurationFileMap { ExeConfigFilename = Environment.CurrentDirectory + @"Configuration\settingsConfiguration.config" }, ConfigurationUserLevel.None);

        public static Configuration SettingsWindowConfiguration { get; } =
            ConfigurationManager.OpenMappedExeConfiguration(
                new ExeConfigurationFileMap { ExeConfigFilename = @"Configuration\settingsWindowConfiguration.config" }, ConfigurationUserLevel.None);
    }


A Configuration folder has been created in the application folder, it contains two files settingsConfiguration.config and settingsWindowConfiguration.config

settingsConfiguration.config (since only it is used so far):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="AutoUpdateProcesses" value="false"/>
  </appSettings>
</configuration>


Right at the start of the application, the ApplicationConfiguration class is used in the main window view model, from which we get the settings object, using the property in the if statement:
Configuration settings = ApplicationConfiguration.SettingsConfiguration;
        public MainVM()
        {
            if(settings.AppSettings.Settings["AutoUpdateProcesses"].Value == "true")
            {
                // We perform the update operation in a separate thread
                Task.Run(() =>
                {
                    // Endless cycle
                    while (true)
                    {
                        Processes = Process.GetProcesses().ToList();
                        Thread.Sleep(4000); // Updating every 4 seconds
                    }
                });
            }
        }


But, on startup, the following exception is thrown:
605ceaf17af02986701836.png

I can't figure out why. Thank you in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question