【问题标题】:How to edit application configuration settings? App.config best way to go?如何编辑应用程序配置设置? App.config 最好的方法是什么?
【发布时间】:2010-10-03 03:34:11
【问题描述】:

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

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

  • 我想知道...最好的是什么 处理自定义设置的最简单方法 对于一个项目——认为这会 不费吹灰之力了解 .Net 处理它......我感到羞耻。

  • 是否可以使用其中一种 设置,AppSettings, ApplicationSettings 或 UserSettings 来处理这个?

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

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

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

更新

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

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

编译时出现只读错误。

【问题讨论】:

  • 由于 App.config 我假设您使用 .NET,您使用的是哪个版本(Visual Studio)?
  • 我正在使用 Visual Studio 2008。

标签: .net configuration settings app-config


【解决方案1】:

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

原文:

我们经常直接在 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>

【讨论】:

  • 我一直直接编辑 app.config。我只是把上面的sn-p放到了app.config中。 configSections 块中的“部分”行定义您自己的部分。
  • 我的错误,我误解了你的问题。我以为您是在尝试配置应用程序,而不是通过 UI 动态配置应用程序。
【解决方案2】:

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

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

【讨论】:

  • 尝试执行此操作时出现只读错误...请参阅问题中的示例。
  • 必须是用户设置:AValue
【解决方案3】:

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

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

使用:

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

代替:

 string mySetting = Settings.Default.MySetting;

对我来说是关键。

【讨论】:

  • 您是说您使用库 project 来存储设置,然后将这些设置用于您的 web project?
  • @DoctorOreo - 实际上我再也不会这样做了。现在我通常会在 ConfigurationManager 或 WebConfigurationManager 周围使用强类型包装器。
【解决方案4】:
【解决方案5】:

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

【讨论】:

  • 是的。应用程序设置是很少更改的设置,只能由管理员修改。用户设置是用户可以根据每个用户修改的设置。 :) 恭喜你弄明白了! :)
【解决方案6】:
 System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

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

用这段代码试试,很简单。

阿特:埃里克·西利扎

【讨论】:

    【解决方案7】:

    试试这个:

    <?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);
        }
    

    【讨论】:

      【解决方案8】:

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

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

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

      【讨论】:

      • 我明白你的意思,但现在我想从 [applicationName].vshost.exe.config 或 [applicationName].exe.config 以外的其他配置文件更新设置值。我可以从其他配置文件(自定义)更新值吗?
      【解决方案9】:

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

      你会看到的是:

      1. 如何读取所有 AppSetting 属性
      2. 如何插入新属性
      3. 如何删除属性
      4. 如何更新属性

      玩得开心!

          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 方面没有任何问题!玩得开心... ;-) !

      【讨论】:

        猜你喜欢
        • 2011-06-06
        • 1970-01-01
        • 2011-11-26
        • 2010-11-20
        • 1970-01-01
        • 2010-10-19
        • 2010-09-19
        • 2010-10-01
        • 1970-01-01
        相关资源
        最近更新 更多