.net 如何编辑应用程序配置设置?App.config 最好的方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/473028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 11:04:39  来源:igfitidea点击:

How to edit application configuration settings? App.config best way to go?

.netconfigurationsettingsapp-config

提问by mattruma

For my project I have settings that I added through the Settings in the project properties.

对于我的项目,我通过项目属性中的设置添加了设置。

I quickly discovered that editing the app.config file directly seems to no really update the settings value. Seems I have to view the project properties when I make a change and then recompile.

我很快发现直接编辑 app.config 文件似乎并没有真正更新设置值。似乎我在进行更改然后重新编译时必须查看项目属性。

  • I'm wondering ... what is the best and easiestway to handle customizable settings for a project -- thought this would be a no-brainerwith how .Net handles it ... shame on me.

  • Is it possible to use one of the settings, AppSettings, ApplicationSettings, or UserSettingsto handle this?

  • 我想知道......处理项目的可自定义设置的最佳和最简单的方法是什么- 认为这对于 .Net 如何处理它是显而易见的......我很惭愧。

  • 是否可以使用AppSettingsApplicationSettingsUserSettings设置之一来处理此问题?

Is it better to just write my settings to custom config file and handle things myself?

将我的设置写入自定义配置文件并自己处理是否更好?

Right now ... I am looking for the quickest solution!

现在......我正在寻找最快的解决方案

My environment is C#, .Net 3.5 and Visual Studio 2008.

我的环境是 C#、.Net 3.5 和 Visual Studio 2008。

Update

更新

I am trying to do the following:

我正在尝试执行以下操作:

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

Gives me a read-only error when I compile.

编译时给我一个只读错误。

采纳答案by mattruma

This is silly ... and I think I am going to have to apologize for wasting everyone's time! But it looks like I just need to set the scope to Userinstead of Application and I can the write the new value.

这很愚蠢……我想我将不得不为浪费大家的时间而道歉!但看起来我只需要将范围设置为 User而不是 Application ,我就可以写入新值。

回答by Peg

I had the same problem until I realized I was running the app in debug mode, therefore my new appSetting's key was being written to the [applicationName].vshost.exe.configfile.

我遇到了同样的问题,直到我意识到我正在调试模式下运行应用程序,因此我的新 appSetting 的密钥被写入 [applicationName]。vshost.exe.config文件。

And this vshost.exe.config file does NOT retain any new keys once the app is closed -- it reverts back to the [applicationName].exe.configfile's contents.

一旦应用程序关闭,这个 vshost.exe.config 文件就不会保留任何新的密钥——它会恢复到 [applicationName]。exe.config文件的内容。

I tested it outside of the debugger, and the various methods here and elsewhere to add a configuration appSetting key work fine. The new key is added to:[applicationName].exe.config.

我在调试器之外测试了它,这里和其他地方的各种方法添加配置 appSetting 键工作正常。新密钥添加到:[applicationName]。exe.config

回答by Dave

I also tried to resolved this need and I have now a nice pretty ConsoleApplication, which i want to share: (App.config)

我也试图解决这个需求,我现在有一个漂亮漂亮的 ConsoleApplication,我想分享:(App.config)

What you will see is:

您将看到的是:

  1. How to read all AppSetting propery
  2. How to insert a new property
  3. How to delete a property
  4. How to update a property
  1. 如何阅读所有 AppSetting 属性
  2. 如何插入新属性
  3. 如何删除属性
  4. 如何更新属性

Have fun!

玩得开心!

    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 File looks like as:

配置文件如下所示:

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

Well, so I didn't have any Problems with AppSettings with this Solution! Have fun... ;-) !

好吧,所以我在使用此解决方案时对 AppSettings 没有任何问题!玩得开心... ;-) !

回答by Dave

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

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

Try with this code , is easy.

试试这个代码,很容易。

Atte: Erick Siliezar

阿特:埃里克·西利扎尔

回答by Jay S

EDIT:My mistake. I misunderstood the purpose of the original question.

编辑:我的错误。我误解了原始问题的目的。

ORIGINAL TEXT:

原文:

We often setup our settings directly in the app.config file, but usually this is for our custom settings.

我们经常直接在 app.config 文件中设置我们的设置,但通常这是我们的自定义设置。

Example 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>

回答by Fredrik Jansson

Not sure if this is what you are after, but you can update and save the setting from the app:

不确定这是否是您所追求的,但您可以从应用程序更新和保存设置:

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

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

回答by tvanfosson

How are you referencing the Settings class in your code? Are you using the default instance or creating a new Settings object? I believe that the default instance uses the designer generated value which is re-read from the configuration file only when the properties are opened. If you create a new object, I believe that the value is read directly from the configuration file itself rather from the designer-generated attribute, unless the setting doesn't exist in the app.config file.

您如何在代码中引用 Settings 类?您是使用默认实例还是创建新的 Settings 对象?我相信默认实例使用设计器生成的值,只有在打开属性时才会从配置文件中重新读取该值。如果您创建一个新对象,我相信该值是直接从配置文件本身而不是从设计器生成的属性中读取的,除非该设置在 app.config 文件中不存在。

Typically my settings will be in a library rather than directly in the application. I set valid defaults in the properties file. I can then override these by adding the appropriate config section (retrieved and modified from the library app.config file) in the application's configuration (either web.config or app.config, as appropriate).

通常我的设置将在库中而不是直接在应用程序中。我在属性文件中设置了有效的默认值。然后,我可以通过在应用程序的配置(web.config 或 app.config,视情况而定)中添加适当的配置部分(从库 app.config 文件中检索和修改)来覆盖这些。

Using:

使用:

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

instead of:

代替:

 string mySetting = Settings.Default.MySetting;

is the key for me.

对我来说是关键。

回答by sumit

Try this:

尝试这个:

<?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>

Reading values from App.Config File:

从 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;
    }

Updating the value in the App.config:

更新 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);
    }