我正在使用C#,赢取表单和.net 2.0
我正在尝试在运行时在用户设置文件中添加一个属性,但我无法在settings.settings文件中查看某个位置的添加属性,即文件存在但未添加属性
当我调用此属性时,我没有收到错误 使用以下代码
MessageBox.Show(***********.Properties.Settings.Default.Properties["NewProperty"].DefaultValue);
我写了以下代码 调用函数
clCommonFuncation cl = new clCommonFuncation();
if (***********.Properties.Settings.Default.Properties["NewProperty"] == null)
{
cl.addPropertyinSettingsFile("NewProperty",
***********.Properties.Settings.Default.Providers,
***********.Properties.Settings.Default.Providers["LocalFileSettingsProvider"],
***********.Properties.Settings.Default.Properties,
typeof(string),"ASD",null);
***********.Properties.Settings.Default.Save();
***********.Properties.Settings.Default.Reload();
}
这就是所谓的行动
public void addPropertyinSettingsFile(string settingName,
SettingsProviderCollection settingsProviderCollection,
SettingsProvider settingsProvider,
SettingsPropertyCollection settingPrpertyCollection,
Type dataType,
object defaultValue,
object settingDefault)
{
SettingsProperty lvSettingProperty = new SettingsProperty(settingName);
lvSettingProperty.DefaultValue = defaultValue;
lvSettingProperty.IsReadOnly = false;
lvSettingProperty.PropertyType = dataType;
lvSettingProperty.Provider = settingsProvider;
lvSettingProperty.SerializeAs = SettingsSerializeAs.String;
lvSettingProperty.Name = settingName;
lvSettingProperty.Attributes.Add(typeof(System.Configuration.UserScopedSettingAttribute),
new System.Configuration.UserScopedSettingAttribute());
settingPrpertyCollection.Add(lvSettingProperty);
}
我做错了什么? 任何建议将不胜感激 谢谢
答案 0 :(得分:1)
我认为您最好使用您的应用程序设置编写自定义struct
或class
并使用序列化进行加载和保存 - 这更加清晰且相关在你的情况下。
答案 1 :(得分:1)
您无法在运行时在.Net设置文件中添加或删除属性。网络上有一些技巧,但它们都不适用,也不是你想要的解决方案。
设置文件并非为此目的而设计。这些文件设计为在设计时填充,仅在运行时“读取”或“修改”。
原因是当您在设计器中创建和编辑设置文件时(通过双击解决方案资源管理器中的设置文件或在项目属性菜单项中选择设置选项卡),Visual Studio将创建一个ApplicationSettings类(从ApplicationSettingsBase类派生),包含您创建的任何设置字段的数据成员以及一些其他属性(如[ApplicationScopedSetting]或[UserScopedSetings])。在运行时,.Net运行时使用此类与seetings文件进行交互。因此,当您尝试在运行时添加属性时,ApplicationSettings类中没有后备文件和属性,并且CLR不知道如何处理它们。
结论:Settings文件具有特定用途,不适用于您的应用程序中的任意配置持久性。尝试使用XML文件,它完全支持您希望从阅读,编写,添加,删除,更新基本类型属性(字符串,字符串,整数等)到使用XML.Seriliazation支持复杂对象。