【问题标题】:Adding a new setting in Settings.setting file在 Settings.setting 文件中添加新设置
【发布时间】:2014-05-19 04:10:00
【问题描述】:

这是我用来向 settings.settings 文件添加新设置的代码,但它不起作用。

System.Configuration.SettingsProperty property = new System.Configuration.SettingsProperty("CustomSetting");

property.DefaultValue = "Default";
property.IsReadOnly = false;
property.PropertyType = typeof(string);
property.Provider = Properties.Settings.Default.Providers["LocalFileSettingsProvider"];
property.Attributes.Add(typeof(System.Configuration.UserScopedSettingAttribute), new System.Configuration.UserScopedSettingAttribute());

Properties.Settings.Default.Properties.Add(property);
// Load settings now.
Properties.Settings.Default.Reload();
// Update the user itnerface.

Properties.Settings.Default["CustomSetting"] = txt_Cipher.Text;
Properties.Settings.Default.Save();
txt_Cipher.Text = string.Empty;

新设置未添加到设置文件中。根据 sumesh 的回复,这是我一直在尝试的新代码。

System.Configuration.SettingsProperty property = new System.Configuration.SettingsProperty("CI");
                Properties.Settings.Default["CI"] = txt_Cipher.Text;
                Properties.Settings.Default.Save();
                Properties.Settings.Default.Reload();
                txt_Cipher.Text = string.Empty;

我已经在 settings.setting 文件中创建了一个设置,如 sumesh 图片中所述。

【问题讨论】:

  • 代码是否抛出异常?
  • 不,它没有,但我在设置文件中看不到任何更改
  • 我认为没有添加自定义设置,因为一旦添加了 Properties.Settings.Default.Properties.Add(property);会抛出键已经存在的错误。
  • 您是在 Settings.settings 中手动添加自定义设置吗?
  • 我在设置文件中添加了一个名为newsetting的设置。那仍然存在,但除此之外没有添加新设置。我也没有任何例外。

标签: c# .net settings


【解决方案1】:

在您的 settings.settings 文件中手动添加 CustomSetting

System.Configuration.SettingsProperty property = new System.Configuration.SettingsProperty("CustomSetting");


Properties.Settings.Default["CustomSetting"] = txt_Cipher.Text;
Properties.Settings.Default.Save();
txt_Cipher.Text = string.Empty;

使用此代码更新设置

它对我来说工作正常,并且为此设置创建了一个 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <WindowsFormsApplication1.Properties.Settings>
            <setting name="CustomSetting" serializeAs="String">
                <value>1</value>
            </setting>
        </WindowsFormsApplication1.Properties.Settings>
    </userSettings>
</configuration>

如图所示请添加海关设置

【讨论】:

  • 在添加自定义设置时,范围应该是什么?
  • 我们可以设置用户级别和应用级别范围
  • 但是当我将范围设置为应用程序级别时,它会显示设置仅获取的错误
  • 您的实际需求是什么?
  • 检查修改?你在你的系统中找到了这样的xml吗?
猜你喜欢
  • 2015-07-19
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多