I am trying to create dynamic settings in a .NET 2.0 C# application. I need
to be able to store settings on the user, but I do not know how many settings
are necessary at design time because the settings are determined by a
business object that is loaded into the app of which there could be one or
many. I would prefer to use the same LocalFileSettingsProvider that the
settings default to so that I do not have to manage it myself.
Here is the code that I currently have:
internal static void SetStringSetting(string name, bool isReadOnly, string
value)
{
SettingsProperty property = new SettingsProperty(name);
property.SerializeAs = SettingsSerializeAs.String;
property.PropertyType = typeof(string);
property.IsReadOnly = isReadOnly;
property.Provider = Properties.Settings.Default.Providers
["LocalFileSettingsProvider"];
SettingsPropertyValue propertyValue = new SettingsPropertyValue(property);
propertyValue.PropertyValue = value;
Properties.Settings.Default.PropertyValues.Add(pro pertyValue);
}
internal static string GetStringSetting(string name)
{
if (Properties.Settings.Default.PropertyValues[name] == null)
return String.Empty;
if (Properties.Settings.Default.PropertyValues[name].PropertyValue == null)
return String.Empty;
return
Properties.Settings.Default.PropertyValues[name].PropertyValue.ToString();
}
This code will create the settings and persist them across the application
session, however, it does not utilize the LocalFileSettingsProvider to save
them to the file. When the application tries to save at close, I also
recieve this error:
Type: ConfigurationErrorsException
Message: The setting {0} does not have either an
ApplicationScopedSettingAttribute or UserScopedSettingAttribute.
I have tried to do:
UserScopedSettingAttribute scopeAttribute = new UserScopedSettingAttribute();
property.Attributes.Add(scopeAttribute, scopeAttribute);
and
UserScopedSettingAttribute scopeAttribute = new UserScopedSettingAttribute();
property.Attributes.Add("UserScopedSettingAttribut e", scopeAttribute);
but I cannot get it to work. Can anyone help me out on this problem?