【问题标题】:Using Application Settings and reading defaults from app.config使用应用程序设置并从 app.config 读取默认值
【发布时间】:2011-02-03 15:42:09
【问题描述】:

我需要使用 ClickOnce 部署来部署 Windows 窗体应用程序。 (VS2008,.NET 3.5) 我需要为这个应用程序提供一个任何用户都可以修改的配置文件。 出于这个原因,我在 app.config 中使用应用程序设置而不是标准 appSetttings,因此我可以将用户配置与应用配置分开。

http://msdn.microsoft.com/en-us/library/ms228995(VS.80).aspx

使用 VS 创建 Settings.settings 文件会生成一个具有硬编码默认值的类,如下所示:

[global::System.Configuration.DefaultSettingValueAttribute("blahblah")]
public string MyProperty
...

我想从 app.config 中读取默认值!

所以我创建了自己的派生自 ApplicationSettingsBase 的类,但我无法让它从 app.config 中读取值。 有什么想法吗?

【问题讨论】:

    标签: c# winforms clickonce


    【解决方案1】:

    我编写了自己的配置类来保留设置。可能对您有帮助的另一件事是,如果您希望在更新 ClickOnce 应用程序时保留设置,我建议您将其放在 ClickOnce 缓存以外的其他位置。这也将使您的用户更容易找到它。本文推荐使用 LocalApplicationData(因为您可以使用 Vista 或 Win7 对其进行写入),但您甚至可能希望将其放在 MyDocuments 下,因为您希望用户能够对其进行编辑。

    http://robindotnet.wordpress.com/2009/08/19/where-do-i-put-my-data-to-keep-it-safe-from-clickonce-updates/

    RobinDotNet

    【讨论】:

      【解决方案2】:

      我实现 ApplicationSettingsBase 如下:

          public class UserSettings : ApplicationSettingsBase
              {
                  private static UserSettings defaultInstance = ((UserSettings)(ApplicationSettingsBase.Synchronized(new UserSettings())));
      
                  public static UserSettings Default
                  {
                      get
                      {
                          return defaultInstance;
                      }
                  }
      
                  [UserScopedSetting()]
                  public string MyProperty
                  {
                      get { return (string)this["MyProperty"]; }
                      set { this["MyProperty"] = (string)value; }
                  }
                  //add more properties
      }
      

      并在 app.config 中添加了正确的 xml...

      http://msdn.microsoft.com/en-us/library/8eyb2ct1(VS.80).aspx

      它有效。 HTH!

      警告!!ApplicationSettingsBase似乎在实现中使用了一些延迟加载。在至少访问一个属性之前,ApplicationSettingsBase.PropertiesApplicationSettingsBase.PropertyValues 集合保持为空。

      UserSettings settings = new UserSettings();
      string temp = settings.MyProperty;//without this line, settings.PropertyValues is empty!! 
      SettingsPropertyValueCollection properties = settings.PropertyValues;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-12
        • 2013-01-09
        • 2011-05-12
        • 2015-11-07
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        相关资源
        最近更新 更多