如何编辑应用程序配置设置?App.config是最好的选择吗?

14

在我的项目中,我通过项目属性中的设置添加了一些设置。

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

  • 我想知道...处理项目可定制设置的最佳和最简单的方法是什么 - 我以为这应该是个易如反掌的事情,看来我错了。

  • 是否可以使用其中一个设置,例如AppSettingsApplicationSettingsUserSettings来处理这个问题?

是编写自定义配置文件并自己处理设置更好呢?

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

我的环境是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)? - thijs
我正在使用Visual Studio 2008。 - mattruma
9个回答

12

这很愚蠢...我想我需要为浪费大家的时间道歉!但看起来我只需要将 范围设置为用户 而不是应用程序,我就可以编写新值了。


1
是的。应用程序设置是很少更改的设置,应该只由管理员修改。用户设置是用户可以根据每个用户的基础进行修改的设置。 :) 很高兴你解决了! :) - Greg D

6
我尝试满足这种需求,并且现在有一个漂亮的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没有任何问题!玩得开心...;-) !


4

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

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

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


我明白你的意思,但现在我想从不同于[applicationName].vshost.exe.config或[applicationName].exe.config的配置文件中更新设置值。我能从其他配置文件(自定义)更新值吗? - ksrds

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

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

尝试使用这段代码,很容易。
致:Erick Siliezar

2

我不确定这是否是你想要的,但你可以从应用程序中更新和保存设置:

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


当我尝试这样做时,我遇到了只读错误...请查看我的问题中的示例。 - mattruma
它必须是用户设置: <userSettings> <ConsoleApplication1.Properties.Settings> <setting name="StringSetting" serializeAs="String"> <value>AValue</value> </setting> </ConsoleApplication1.Properties.Settings> </userSettings> - Fredrik Jansson

2

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

原文:

我们经常在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文件。我刚刚将上面的代码片段放入了app.config文件中。configSections块中的“section”行定义了您自己的部分。 - Jay S
我的错误,我误解了你的问题。我以为你试图配置应用程序,而不是通过用户界面动态配置应用程序。 - Jay S

2
你在代码中是如何引用Settings类的?你是使用默认实例还是创建了一个新的Settings对象?我相信默认实例使用设计师生成的值,只有当属性被打开时才会从配置文件重新读取。如果你创建了一个新的对象,我相信该值将直接从配置文件本身读取,而不是从设计师生成的属性中读取,除非该设置不存在于app.config文件中。
通常我的设置会在库中而不是直接在应用程序中。我在属性文件中设置有效的默认值。然后,我可以通过在应用程序的配置中添加适当的配置部分(从库app.config文件检索和修改)来覆盖这些值(无论是web.config还是app.config)。
使用:
 Settings configuration = new Settings();
 string mySetting = configuration.MySetting;

改为:

 string mySetting = Settings.Default.MySetting;

"

对我来说,技术是关键。

"

你是说你使用一个库项目来存储设置,然后在你的Web 项目中使用这些设置吗? - Cody
@DoctorOreo - 实际上我不再这样做了。现在我通常会使用一个强类型的 ConfigurationManager 或 WebConfigurationManager 包装器。 - tvanfosson

1

试试这个:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接