For my project I have settings that I added through the Settings in the project properties.
对于我的项目,我有通过项目属性中的“设置”添加的设置。
I quickly discovered that editing the app.config file directly seems to no really update the settings value. Seems I have to view the project properties when I make a change and then recompile.
我很快发现直接编辑app.config文件似乎没有真正更新设置值。似乎我在进行更改然后重新编译时必须查看项目属性。
-
I'm wondering ... what is the best and easiest way to handle customizable settings for a project -- thought this would be a no-brainer with how .Net handles it ... shame on me.
我想知道......处理项目的可自定义设置的最佳和最简单的方法是什么 - 认为这对于.Net如何处理它是一个明智的选择......让我感到羞耻。
-
Is it possible to use one of the settings, AppSettings, ApplicationSettings, or UserSettings to handle this?
是否可以使用其中一个设置,AppSettings,ApplicationSettings或UserSettings来处理这个问题?
Is it better to just write my settings to custom config file and handle things myself?
将我的设置写入自定义配置文件并自行处理是否更好?
Right now ... I am looking for the quickest solution!
现在......我正在寻找最快的解决方案!
My environment is C#, .Net 3.5 and Visual Studio 2008.
我的环境是C#,。Net 3.5和Visual Studio 2008。
Update
I am trying to do the following:
我正在尝试执行以下操作:
protected override void Save()
{
Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
Properties.Settings.Default.Save();
}
Gives me a read-only error when I compile.
编译时给我一个只读错误。
9 个解决方案
#1
10
This is silly ... and I think I am going to have to apologize for wasting everyone's time! But it looks like I just need to set the scope to User instead of Application and I can the write the new value.
这很愚蠢......我想我不得不为浪费每个人的时间而道歉!但看起来我只需要将范围设置为User而不是Application,我可以编写新值。
#2
3
System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["oldPlace"].Value = "3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Try with this code , is easy.
尝试使用此代码很容易。
Atte: Erick Siliezar
Atte:Erick Siliezar
#3
3
I had the same problem until I realized I was running the app in debug mode, therefore my new appSetting's key was being written to the [applicationName].vshost.exe.config file.
我遇到了同样的问题,直到我意识到我在调试模式下运行应用程序,因此我的新appSetting的密钥被写入[applicationName] .vshost.exe.config文件。
And this vshost.exe.config file does NOT retain any new keys once the app is closed -- it reverts back to the [applicationName].exe.config file's contents.
此应用程序关闭后,此vshost.exe.config文件不会保留任何新密钥 - 它将恢复为[applicationName] .exe.config文件的内容。
I tested it outside of the debugger, and the various methods here and elsewhere to add a configuration appSetting key work fine. The new key is added to:[applicationName].exe.config.
我在调试器之外测试了它,并在这里和其他地方添加配置appSetting键的各种方法工作正常。新密钥将添加到:[applicationName] .exe.config。
#4
3
I also tried to resolved this need and I have now a nice pretty ConsoleApplication, which i want to share: (App.config)
我也试图解决这个需求,现在我有一个漂亮的漂亮的ConsoleApplication,我想分享:(App.config)
What you will see is:
你会看到的是:
- How to read all AppSetting propery
- How to insert a new property
- How to delete a property
- How to update a property
如何阅读所有AppSetting propery
如何插入新属性
如何删除属性
如何更新属性
Have fun!
public void UpdateProperty(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
// update SaveBeforeExit
config.AppSettings.Settings[key].Value = value;
Console.Write("...Configuration updated: key "+key+", value: "+value+"...");
//save the file
config.Save(ConfigurationSaveMode.Modified);
Console.Write("...saved Configuration...");
//relaod the section you modified
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
Console.Write("...Configuration Section refreshed...");
}
public void ReadAppSettingsProperty()
{
try
{
var section = ConfigurationManager.GetSection("applicationSettings");
// Get the AppSettings section.
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// Get the AppSettings section elements.
Console.WriteLine();
Console.WriteLine("Using AppSettings property.");
Console.WriteLine("Application settings:");
if (appSettings.Count == 0)
{
Console.WriteLine("[ReadAppSettings: {0}]", "AppSettings is empty Use GetSection command first.");
}
for (int i = 0; i < appSettings.Count; i++)
{
Console.WriteLine("#{0} Key: {1} Value: {2}",
i, appSettings.GetKey(i), appSettings[i]);
}
}
catch (ConfigurationErrorsException e)
{
Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
}
}
public void updateAppSettingProperty(string key, string value)
{
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string sectionName = "appSettings";
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
SaveConfigFile(config);
}
public void insertAppSettingProperty(string key, string value)
{
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string sectionName = "appSettings";
config.AppSettings.Settings.Add(key, value);
SaveConfigFile(config);
}
public void deleteAppSettingProperty(string key)
{
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
SaveConfigFile(config);
}
private static void SaveConfigFile(System.Configuration.Configuration config)
{
string sectionName = "appSettings";
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of the changed section. This
// makes the new values available for reading.
ConfigurationManager.RefreshSection(sectionName);
// Get the AppSettings section.
AppSettingsSection appSettingSection =
(AppSettingsSection)config.GetSection(sectionName);
Console.WriteLine();
Console.WriteLine("Using GetSection(string).");
Console.WriteLine("AppSettings section:");
Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());
}
}
Configuration File looks like as:
配置文件如下所示:
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="aNewKey1" value="aNewValue1" />
</appSettings>
Well, so I didn't have any Problems with AppSettings with this Solution! Have fun... ;-) !
好吧,所以我对这个解决方案的AppSettings没有任何问题!玩的开心... ;-) !
#5
2
Not sure if this is what you are after, but you can update and save the setting from the app:
不确定这是否是您所追求的,但您可以从应用程序更新并保存设置:
ConsoleApplication1.Properties.Settings.Default.StringSetting = "test"; ConsoleApplication1.Properties.Settings.Default.Save();
ConsoleApplication1.Properties.Settings.Default.StringSetting =“test”; ConsoleApplication1.Properties.Settings.Default.Save();
#6
2
How are you referencing the Settings class in your code? Are you using the default instance or creating a new Settings object? I believe that the default instance uses the designer generated value which is re-read from the configuration file only when the properties are opened. If you create a new object, I believe that the value is read directly from the configuration file itself rather from the designer-generated attribute, unless the setting doesn't exist in the app.config file.
你是如何在代码中引用Settings类的?您使用默认实例还是创建新的Settings对象?我相信默认实例使用设计器生成的值,只有在打开属性时才会从配置文件中重新读取该值。如果您创建一个新对象,我相信该值直接从配置文件本身读取,而不是从设计器生成的属性读取,除非app.config文件中不存在该设置。
Typically my settings will be in a library rather than directly in the application. I set valid defaults in the properties file. I can then override these by adding the appropriate config section (retrieved and modified from the library app.config file) in the application's configuration (either web.config or app.config, as appropriate).
通常,我的设置将在库中,而不是直接在应用程序中。我在属性文件中设置了有效的默认值。然后我可以通过在应用程序的配置中添加适当的配置部分(从库app.config文件中检索和修改)来覆盖它们(如果适用,可以是web.config或app.config)。
Using:
Settings configuration = new Settings();
string mySetting = configuration.MySetting;
instead of:
string mySetting = Settings.Default.MySetting;
is the key for me.
对我来说是关键。
#7
2
EDIT: My mistake. I misunderstood the purpose of the original question.
编辑:我的错。我误解了原问题的目的。
ORIGINAL TEXT:
We often setup our settings directly in the app.config file, but usually this is for our custom settings.
我们经常直接在app.config文件中设置我们的设置,但通常这是我们的自定义设置。
Example app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
</connectionStrings>
<MySection>
<add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
<add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
<add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
</MySection>
</configuration>
#8
1
Try this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!--- ->
</configSections>
<userSettings>
<Properties.Settings>
<setting name="MainFormSize" serializeAs="String">
<value>
1022, 732</value>
</setting>
<Properties.Settings>
</userSettings>
<appSettings>
<add key="TrilWareMode" value="-1" />
<add key="OptionsPortNumber" value="1107" />
</appSettings>
</configuration>
Reading values from App.Config File:
从App.Config文件中读取值:
//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private int LoadConfigData ()
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
// AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
// points to the config file.
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
int smartRefreshPortNumber = 0;
foreach (XmlNode node in doc.ChildNodes.Item(1))
{
//Searching for the node “”
if (node.LocalName == "appSettings")
{
smartPortNumber =Convert.ToInt32(node.ChildNodes.Item(1).Attributes[1].Value);
}
}
Return smartPortNumber;
}
Updating the value in the App.config:
更新App.config中的值:
//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private void UpdateConfigData()
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
//Looping through all nodes.
foreach (XmlNode node in doc.ChildNodes.Item(1))
{
//Searching for the node “”
if (node.LocalName == "appSettings")
{
if (!dynamicRefreshCheckBox.Checked)
{
node.ChildNodes.Item(1).Attributes[1].Value = this.portNumberTextBox.Text;
}
else
{
node.ChildNodes.Item(1).Attributes[1].Value = Convert.ToString(0);
}
}
}
//Saving the Updated values in App.config File.Here updating the config
//file in the same path.
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
#9
0
Your answer is probably here: Simplest way to have a configuration file in a Windows Forms C# Application
您的答案可能就在这里:在Windows Forms C#应用程序中拥有配置文件的最简单方法
#1
10
This is silly ... and I think I am going to have to apologize for wasting everyone's time! But it looks like I just need to set the scope to User instead of Application and I can the write the new value.
这很愚蠢......我想我不得不为浪费每个人的时间而道歉!但看起来我只需要将范围设置为User而不是Application,我可以编写新值。
#2
3
System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["oldPlace"].Value = "3";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Try with this code , is easy.
尝试使用此代码很容易。
Atte: Erick Siliezar
Atte:Erick Siliezar
#3
3
I had the same problem until I realized I was running the app in debug mode, therefore my new appSetting's key was being written to the [applicationName].vshost.exe.config file.
我遇到了同样的问题,直到我意识到我在调试模式下运行应用程序,因此我的新appSetting的密钥被写入[applicationName] .vshost.exe.config文件。
And this vshost.exe.config file does NOT retain any new keys once the app is closed -- it reverts back to the [applicationName].exe.config file's contents.
此应用程序关闭后,此vshost.exe.config文件不会保留任何新密钥 - 它将恢复为[applicationName] .exe.config文件的内容。
I tested it outside of the debugger, and the various methods here and elsewhere to add a configuration appSetting key work fine. The new key is added to:[applicationName].exe.config.
我在调试器之外测试了它,并在这里和其他地方添加配置appSetting键的各种方法工作正常。新密钥将添加到:[applicationName] .exe.config。
#4
3
I also tried to resolved this need and I have now a nice pretty ConsoleApplication, which i want to share: (App.config)
我也试图解决这个需求,现在我有一个漂亮的漂亮的ConsoleApplication,我想分享:(App.config)
What you will see is:
你会看到的是:
- How to read all AppSetting propery
- How to insert a new property
- How to delete a property
- How to update a property
如何阅读所有AppSetting propery
如何插入新属性
如何删除属性
如何更新属性
Have fun!
public void UpdateProperty(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
// update SaveBeforeExit
config.AppSettings.Settings[key].Value = value;
Console.Write("...Configuration updated: key "+key+", value: "+value+"...");
//save the file
config.Save(ConfigurationSaveMode.Modified);
Console.Write("...saved Configuration...");
//relaod the section you modified
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
Console.Write("...Configuration Section refreshed...");
}
public void ReadAppSettingsProperty()
{
try
{
var section = ConfigurationManager.GetSection("applicationSettings");
// Get the AppSettings section.
NameValueCollection appSettings = ConfigurationManager.AppSettings;
// Get the AppSettings section elements.
Console.WriteLine();
Console.WriteLine("Using AppSettings property.");
Console.WriteLine("Application settings:");
if (appSettings.Count == 0)
{
Console.WriteLine("[ReadAppSettings: {0}]", "AppSettings is empty Use GetSection command first.");
}
for (int i = 0; i < appSettings.Count; i++)
{
Console.WriteLine("#{0} Key: {1} Value: {2}",
i, appSettings.GetKey(i), appSettings[i]);
}
}
catch (ConfigurationErrorsException e)
{
Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
}
}
public void updateAppSettingProperty(string key, string value)
{
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string sectionName = "appSettings";
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
SaveConfigFile(config);
}
public void insertAppSettingProperty(string key, string value)
{
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string sectionName = "appSettings";
config.AppSettings.Settings.Add(key, value);
SaveConfigFile(config);
}
public void deleteAppSettingProperty(string key)
{
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
SaveConfigFile(config);
}
private static void SaveConfigFile(System.Configuration.Configuration config)
{
string sectionName = "appSettings";
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of the changed section. This
// makes the new values available for reading.
ConfigurationManager.RefreshSection(sectionName);
// Get the AppSettings section.
AppSettingsSection appSettingSection =
(AppSettingsSection)config.GetSection(sectionName);
Console.WriteLine();
Console.WriteLine("Using GetSection(string).");
Console.WriteLine("AppSettings section:");
Console.WriteLine(appSettingSection.SectionInformation.GetRawXml());
}
}
Configuration File looks like as:
配置文件如下所示:
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="aNewKey1" value="aNewValue1" />
</appSettings>
Well, so I didn't have any Problems with AppSettings with this Solution! Have fun... ;-) !
好吧,所以我对这个解决方案的AppSettings没有任何问题!玩的开心... ;-) !
#5
2
Not sure if this is what you are after, but you can update and save the setting from the app:
不确定这是否是您所追求的,但您可以从应用程序更新并保存设置:
ConsoleApplication1.Properties.Settings.Default.StringSetting = "test"; ConsoleApplication1.Properties.Settings.Default.Save();
ConsoleApplication1.Properties.Settings.Default.StringSetting =“test”; ConsoleApplication1.Properties.Settings.Default.Save();
#6
2
How are you referencing the Settings class in your code? Are you using the default instance or creating a new Settings object? I believe that the default instance uses the designer generated value which is re-read from the configuration file only when the properties are opened. If you create a new object, I believe that the value is read directly from the configuration file itself rather from the designer-generated attribute, unless the setting doesn't exist in the app.config file.
你是如何在代码中引用Settings类的?您使用默认实例还是创建新的Settings对象?我相信默认实例使用设计器生成的值,只有在打开属性时才会从配置文件中重新读取该值。如果您创建一个新对象,我相信该值直接从配置文件本身读取,而不是从设计器生成的属性读取,除非app.config文件中不存在该设置。
Typically my settings will be in a library rather than directly in the application. I set valid defaults in the properties file. I can then override these by adding the appropriate config section (retrieved and modified from the library app.config file) in the application's configuration (either web.config or app.config, as appropriate).
通常,我的设置将在库中,而不是直接在应用程序中。我在属性文件中设置了有效的默认值。然后我可以通过在应用程序的配置中添加适当的配置部分(从库app.config文件中检索和修改)来覆盖它们(如果适用,可以是web.config或app.config)。
Using:
Settings configuration = new Settings();
string mySetting = configuration.MySetting;
instead of:
string mySetting = Settings.Default.MySetting;
is the key for me.
对我来说是关键。
#7
2
EDIT: My mistake. I misunderstood the purpose of the original question.
编辑:我的错。我误解了原问题的目的。
ORIGINAL TEXT:
We often setup our settings directly in the app.config file, but usually this is for our custom settings.
我们经常直接在app.config文件中设置我们的设置,但通常这是我们的自定义设置。
Example app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MySection" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="Default" connectionString="server=MyServer;database=MyDatabase;uid=MyDBUser;password=MyDBPassword;connection timeout=20" providerName="System.Data.SqlClient" />
</connectionStrings>
<MySection>
<add key="RootPath" value="C:\MyDirectory\MyRootFolder" /> <!-- Path to the root folder. -->
<add key="SubDirectory" value="MySubDirectory" /> <!-- Name of the sub-directory. -->
<add key="DoStuff" value="false" /> <!-- Specify if we should do stuff -->
</MySection>
</configuration>
#8
1
Try this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!--- ->
</configSections>
<userSettings>
<Properties.Settings>
<setting name="MainFormSize" serializeAs="String">
<value>
1022, 732</value>
</setting>
<Properties.Settings>
</userSettings>
<appSettings>
<add key="TrilWareMode" value="-1" />
<add key="OptionsPortNumber" value="1107" />
</appSettings>
</configuration>
Reading values from App.Config File:
从App.Config文件中读取值:
//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private int LoadConfigData ()
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
// AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
// points to the config file.
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
int smartRefreshPortNumber = 0;
foreach (XmlNode node in doc.ChildNodes.Item(1))
{
//Searching for the node “”
if (node.LocalName == "appSettings")
{
smartPortNumber =Convert.ToInt32(node.ChildNodes.Item(1).Attributes[1].Value);
}
}
Return smartPortNumber;
}
Updating the value in the App.config:
更新App.config中的值:
//This method will read the value of the OptionsPortNumber in the
//above app.config file.
private void UpdateConfigData()
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
//Looping through all nodes.
foreach (XmlNode node in doc.ChildNodes.Item(1))
{
//Searching for the node “”
if (node.LocalName == "appSettings")
{
if (!dynamicRefreshCheckBox.Checked)
{
node.ChildNodes.Item(1).Attributes[1].Value = this.portNumberTextBox.Text;
}
else
{
node.ChildNodes.Item(1).Attributes[1].Value = Convert.ToString(0);
}
}
}
//Saving the Updated values in App.config File.Here updating the config
//file in the same path.
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
#9
0
Your answer is probably here: Simplest way to have a configuration file in a Windows Forms C# Application
您的答案可能就在这里:在Windows Forms C#应用程序中拥有配置文件的最简单方法