Как изменить настройки конфигурации приложения? App.config лучший способ пойти?

В моем проекте у меня есть настройки, которые я добавил с помощью настроек в свойствах проекта.

Я быстро обнаружил, что редактирование файла app.config напрямую не обновляет значение настроек. Кажется, мне нужно просмотреть свойства проекта, когда я делаю изменения, а затем перекомпилирую.

  • Мне интересно... что такое лучший и самый простой способ справиться с настраиваемыми настройками для проекта - думал, что это быть без проблем с тем, как .Net обрабатывает его... стыдно за меня.

  • Можно ли использовать один из настройки, AppSettings, ApplicationSettings или UserSettings, чтобы справиться с этим?

Лучше ли просто писать мои настройки в пользовательский файл конфигурации и самостоятельно обрабатывать вещи?

Прямо сейчас... Я ищу быстрое решение!

Моя среда - это С#,.Net 3.5 и Visual Studio 2008.

Update

Я пытаюсь сделать следующее:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Дает мне ошибку только для чтения при компиляции.

Ответ 1

Это глупо... и я думаю, что мне придется извиниться за то, что тратило все время! Но похоже, что мне просто нужно установить область для пользователя вместо приложения, и я могу написать новое значение.

Ответ 2

 System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        config.AppSettings.Settings["oldPlace"].Value = "3";     
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

Попробуйте с этим кодом, легко.

Атте: Эрик Силизар

Ответ 3

У меня была такая же проблема, пока я не понял, что запускаю приложение в режиме отладки, поэтому новый ключ appSetting записывался в файл [applicationName]. vshost.exe.config.

И этот файл vshost.exe.config НЕ сохраняет новые ключи после закрытия приложения - он возвращается к содержимому [applicationName]. exe.config.

Я тестировал его вне отладчика, и различные методы здесь и в других местах для добавления ключа конфигурации appSetting работают нормально. Новый ключ добавляется к: [applicationName]. exe.config.

Ответ 4

Я также попытался решить эту проблему, и теперь у меня есть приятная консольная консоль, которую я хочу поделиться: (App.config)

Что вы увидите:

  • Как читать все свойства AppSetting
  • Как вставить новое свойство
  • Как удалить свойство
  • Как обновить свойство

Удачи!

    public void UpdateProperty(string key, string value)
    {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;


        // update SaveBeforeExit
        config.AppSettings.Settings[key].Value = value;
        Console.Write("...Configuration updated: key "+key+", value: "+value+"...");

        //save the file
        config.Save(ConfigurationSaveMode.Modified);
        Console.Write("...saved Configuration...");
        //relaod the section you modified
        ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
        Console.Write("...Configuration Section refreshed...");
    }

    public void ReadAppSettingsProperty()
    {
        try
        {
            var section = ConfigurationManager.GetSection("applicationSettings");

            // Get the AppSettings section.
            NameValueCollection appSettings = ConfigurationManager.AppSettings;

            // Get the AppSettings section elements.
            Console.WriteLine();
            Console.WriteLine("Using AppSettings property.");
            Console.WriteLine("Application settings:");

            if (appSettings.Count == 0)
            {
            Console.WriteLine("[ReadAppSettings: {0}]", "AppSettings is empty Use GetSection command first.");
            }
            for (int i = 0; i < appSettings.Count; i++)
            {
                Console.WriteLine("#{0} Key: {1} Value: {2}",
                i, appSettings.GetKey(i), appSettings[i]);
            }
        }
        catch (ConfigurationErrorsException e)
        {
            Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
        }

    }


    public void updateAppSettingProperty(string key, string value)
    {
        // Get the application configuration file.
        System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        string sectionName = "appSettings";


        config.AppSettings.Settings.Remove(key);
        config.AppSettings.Settings.Add(key, value);

        SaveConfigFile(config);
    }

    public void insertAppSettingProperty(string key, string value)
    {
        // Get the application configuration file.
        System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        string sectionName = "appSettings";

        config.AppSettings.Settings.Add(key, value);

        SaveConfigFile(config);
    }

    public void deleteAppSettingProperty(string key)
    {
        // Get the application configuration file.
        System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.Settings.Remove(key);

        SaveConfigFile(config);
    }

    private static void SaveConfigFile(System.Configuration.Configuration config)
    {
        string sectionName = "appSettings";

        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);

        // Force a reload of the changed section. This  
        // makes the new values available for reading.
        ConfigurationManager.RefreshSection(sectionName);

        // Get the AppSettings section.
        AppSettingsSection appSettingSection =
          (AppSettingsSection)config.GetSection(sectionName);

        Console.WriteLine();
        Console.WriteLine("Using GetSection(string).");
        Console.WriteLine("AppSettings section:");
        Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());
    }    
}

Файл конфигурации выглядит так:

<configuration>
<configSections>
</configSections>
<appSettings>
    <add key="aNewKey1" value="aNewValue1" />
</appSettings>

Хорошо, поэтому у меня не было проблем с AppSettings с этим решением! Получайте удовольствие...;-)!

Ответ 5

ИЗМЕНИТЬ: Моя ошибка. Я неправильно понял цель первоначального вопроса.

ОРИГИНАЛЬНЫЙ ТЕКСТ:

Мы часто настраиваем наши настройки непосредственно в файле app.config, но обычно это относится к нашим пользовательским настройкам.

Пример app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </configSections>
    <connectionStrings>
        <add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
    </connectionStrings>
    <MySection>
        <add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
        <add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
        <add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
    </MySection>
</configuration>

Ответ 6

Не уверен, что это то, что вам нужно, но вы можете обновить и сохранить настройки из приложения:

ConsoleApplication1.Properties.Settings.Default.StringSetting = "test"; ConsoleApplication1.Properties.Settings.Default.Save();

Ответ 7

Как вы ссылаетесь на класс настроек в своем коде? Вы используете экземпляр по умолчанию или создаете новый объект настроек? Я считаю, что экземпляр по умолчанию использует созданное конструктором значение, которое перечитывается из файла конфигурации только при открытии свойств. Если вы создаете новый объект, я считаю, что значение считывается непосредственно из самого файла конфигурации, а не из созданного конструктором атрибута, если этот параметр не существует в файле app.config.

Обычно мои настройки будут находиться в библиотеке, а не непосредственно в приложении. Я устанавливаю допустимые значения по умолчанию в файле свойств. Затем я могу переопределить их, добавив в конфигурацию приложения соответствующий конфигурационный раздел (извлеченный и измененный из файла библиотеки app.config) (либо web.config, либо app.config, если это необходимо).

Использование:

 Settings configuration = new Settings();
 string mySetting = configuration.MySetting;

вместо:

 string mySetting = Settings.Default.MySetting;

- ключ для меня.

Ответ 8

Попробуйте следующее:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
   <!--- ->
  </configSections>

  <userSettings>
   <Properties.Settings>
      <setting name="MainFormSize" serializeAs="String">
        <value>
1022, 732</value>
      </setting>
   <Properties.Settings>
  </userSettings>

  <appSettings>
    <add key="TrilWareMode" value="-1" />
    <add key="OptionsPortNumber" value="1107" />
  </appSettings>

</configuration>

Чтение значений из файла App.Config:

//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private int LoadConfigData ()
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        // AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
        // points to the config file.   
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        int smartRefreshPortNumber = 0;
        foreach (XmlNode node in doc.ChildNodes.Item(1))
        {
        //Searching for the node ""
            if (node.LocalName == "appSettings")
            {
                 smartPortNumber =Convert.ToInt32(node.ChildNodes.Item(1).Attributes[1].Value);
            }
        }
        Return smartPortNumber;
    }

Обновление значения в App.config:

//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private void UpdateConfigData()
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);


        //Looping through all nodes.
        foreach (XmlNode node in doc.ChildNodes.Item(1))
        {
        //Searching for the node ""
            if (node.LocalName == "appSettings")
            {
                if (!dynamicRefreshCheckBox.Checked)
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = this.portNumberTextBox.Text;
                }
                else
                {
                    node.ChildNodes.Item(1).Attributes[1].Value = Convert.ToString(0);
                }
            }
        }
        //Saving the Updated values in App.config File.Here updating the config
        //file in the same path.
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }