2014-04-07 22 views
2

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

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在图像中所述。

+0

该代码是否会抛出任何异常? – Sumeshk

+0

不,它不,但我不能看到设置文件中的任何更改 – wintersolider

+0

我认为没有添加CustomSetting,因为一旦它被添加Properties.Settings.Default.Properties.Add(property);会抛出键已经存在的错误。 – Sumeshk

回答

1

添加CustomSetting手动您settings.settings文件

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> 

enter image description here

请认真阅读e如图所示添加customsSettings

+0

虽然添加自定义设置应该是什么范围? – wintersolider

+0

我们可以设置用户级别和应用程序级别范围 – Sumeshk

+0

但是,当我将范围设置为应用程序级别时,它显示错误的设置是只得到 – wintersolider

相关问题