2008-10-14 69 views
5

我创建了一个动态地将SettingsProperty添加到.NET文件中的方法app.config。这一切都很好,但是当我下次启动应用程序时,只能看到设计器中创建的属性。我如何加载属性运行时?下次如何加载动态创建的设置属性?

我为创建SettingsProperty代码如下所示:

internal void CreateProperty<T>(string propertyName) 
{ 
    string providerName = "LocalFileSettingsProvider"; 
    System.Configuration.SettingsAttributeDictionary attributes = new SettingsAttributeDictionary(); 
    System.Configuration.UserScopedSettingAttribute attr = new UserScopedSettingAttribute(); 

    attributes.Add(attr.TypeId, attr); 

    System.Configuration.SettingsProperty prop; 
    SettingsProvider provider = ApplicationEnvironment.GlobalSettings.Providers[providerName]; 

    prop = new System.Configuration.SettingsProperty(
     propertyName, 
     typeof(T), 
     provider, 
     false, 
     default(T), 
     System.Configuration.SettingsSerializeAs.String, 
     attributes, 
     false, 
     false 
    ); 

    ApplicationEnvironment.GlobalSettings.Properties.Add(prop); 
    ApplicationEnvironment.GlobalSettings.Reload(); 
} 

当下来看,我问的设置属性我找不到任何previosuly创建的属性。无论我是否拨打ApplicationEnvironment.GlobalSettings.Reload();

回答

1

用户定义的配置设置绑定到它们创建的程序集版本。如果您有滚动版本号(例如1.0。),则会丢失上次运行的设置。

1

我遇到了同样的问题。恕我直言问题是,.NET System.Configuration.SettingsBase对象使用反射来确定应从永久存储器加载的属性的名称,类型等。当你添加一个动态设置属性时,这个信息就会丢失。所以你需要在设置属性定义之前不仅添加保存的值,还需要在你之前读取它。根据你的情况,应该是这样的

... 
// the name and type of the property being read must be known at this point 
CreateProperty<T>(propertyName); 
ApplicationEnvironment.GlobalSettings.Reload(); 
T propertyValue = ApplicationEnvironment.GlobalSettings[propertyName]; 

您可能需要调用开头的CreateProperty方法为所有要使用,然后调用Reload只有一次的性质。在这两种情况下,您都需要知道属性的名称和类型。