在应用程序间共享设置

时间:2010-07-29 22:35:58

标签: c# .net configuration settings

我有多个.NET程序集,它们都需要共享常用的用户设置,例如首选项,用户名等。一个是WPF应用程序,另一个是控制台应用程序,第三个是Office加载项。所有这些设置都是用户范围。

只有WPF应用程序需要能够更改设置。其余的只是阅读它们。

理想情况下,我想使用.NET配置框架。我不知道该怎么做。如果我将设置添加到WPF应用程序,其他应用程序如何找到user.config文件?

创建类库并使用IsolatedFileStorage并序列化我的设置会更容易吗?

非常感谢任何建议。

1 个答案:

答案 0 :(得分:2)

You can implement your custom settings class, inheriting ApplicationSettingsBase. As a good start, you can add the default User Settings file to a sample project (Right click on the project -> Properties -> Settings -> This project does not contain a default settings file. Click here to create one.). Add a user-scoped setting and investigate the structure of the designer-generated Settings.Designer.cs file:

namespace ConsoleApplication1.Properties {


    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("John Doe")]
        public string Name {
            get {
                return ((string)(this["Name"]));
            }
            set {
                this["Name"] = value;
            }
        }
    }
}

In your custom implementation, you will not be limited to the designer-generated access modifiers, so you can implement the Settings class as internal with internal setters, visible only to the needed assemblies, or whatever fits your needs.

Of course, you can always implement your custom serialize/deserialize mechanism, but you will lose the funcionality provided by ApplicationSettingsBase's Updgrade, Reload, and Reset methods. If you don't need any of these, this could be the cleaner approach.

相关问题