c#:在运行时创建新设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/175726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c#: Create new settings at run time
提问by
c# windows forms: How do you create new settings at run time so that they are permanently saved as Settings.Default.-- values?
c# windows 窗体:如何在运行时创建新设置,以便将它们永久保存为 Settings.Default.-- 值?
回答by OregonGhost
Since the Settings class is generated at build time (or, actually, whenever you update the settings file from within the designer), you can't use this mechanism for dynamic scenarios. You can, however, add some collection or dictionary to the application settings and modify that dynamically.
由于 Settings 类是在构建时生成的(或者,实际上,每当您从设计器中更新设置文件时),您不能将此机制用于动态场景。但是,您可以向应用程序设置添加一些集合或字典并动态修改它。
回答by Chris Marasti-Georg
How would you access the new settings that you have created? The point of the Visual Studio settings designer is that you can write code that uses these settings with compile-time checking of your code. If you want to dynamically create new settings for your app to use, you will also need to dynamically load them. For dynamic settings, you may want to look at the System.Configuration assembly, notably ConfigurationSection. You can create a custom configuration section with that, which you could use for dynamic setting addition/removal. You might use a ConfigurationCollectionfor that dynamic addition/removal.
您将如何访问您创建的新设置?Visual Studio 设置设计器的重点是,您可以编写使用这些设置的代码,并对代码进行编译时检查。如果您想为您的应用动态创建新设置以供使用,您还需要动态加载它们。对于动态设置,您可能需要查看 System.Configuration 程序集,尤其是ConfigurationSection。您可以使用它创建一个自定义配置部分,您可以将其用于动态设置添加/删除。您可以使用ConfigurationCollection进行动态添加/删除。
INI files eh? Google turned up this INI libraryfor .NET.
INI 文件啊?Google为 .NET 提供了这个 INI 库。
回答by Chris Marasti-Georg
I see how what I wanted was the wrong idea. I'm porting a c++ app over to c# and it has a lot of ini file settings and I was looking for a shortcut to add them in. I'm lazy.
我明白我想要的是错误的想法。我正在将一个 c++ 应用程序移植到 c# 上,它有很多 ini 文件设置,我正在寻找添加它们的快捷方式。我很懒惰。
回答by Chris Marasti-Georg
What you could do is create a new registry key. Name the new key "Your program settings".
您可以做的是创建一个新的注册表项。将新键命名为“您的程序设置”。
RegistryKey ProgSettings = Registry.CurrentUser.OpenSubKey("Software", true);
ProgSettings.CreateSubKey("Your Program settings");
ProgSettings.Close();
Now you can add String Identifiers and values.
现在您可以添加字符串标识符和值。
RegistryKey ProgSettings = Registry.CurrentUser.OpenSubKey("Software\Your Program settings", true);
ProgSettings.SetValue("Setting Name", value); // store settings
string settings = ProgSettings.GetValue("Setting Name", false); // retreave settings
ProgSettings.DeleteValue("Setting Name", false);
Besure to close the registry key when you are done to avoid conflicts with other parts of your program that may write to the registry.
完成后请务必关闭注册表项,以避免与可能写入注册表的程序的其他部分发生冲突。
Many comercial software applications use these methods. stackoverflow has many examples about writing and reading to the registry. This is much easyer then modifying the appconfig.xml file that is used when you create settings.
许多商业软件应用程序使用这些方法。stackoverflow 有许多关于写入和读取注册表的示例。这比修改创建设置时使用的 appconfig.xml 文件要容易得多。
回答by Tom Wilson
You can't add settings directly (at least not without editing the config XML at runtime), but you can fake it.
您不能直接添加设置(至少在运行时不编辑配置 XML 时不能),但您可以伪造它。
In my case, I had a group of identical custom controls on the form, and I wanted to store the runtime state of each control. I needed to store the state of each control, since each one had different data it.
就我而言,我在表单上有一组相同的自定义控件,我想存储每个控件的运行时状态。我需要存储每个控件的状态,因为每个控件都有不同的数据。
I created a new StringCollection setting named ControlDataand placed my own data in there. I then load the data from that list and use it to initialize my controls.
我创建了一个名为ControlData的新 StringCollection 设置并将我自己的数据放在那里。然后我从该列表加载数据并使用它来初始化我的控件。
The list looks like this:
该列表如下所示:
Box1Text=A
Box1List=abc;def;foo;bar;
Box2Text=hello
Box2List=server1;server2;
In my startup code, I read through the key/value pairs like this:
在我的启动代码中,我通读了这样的键/值对:
foreach (string item in Properties.Settings.Default.ControlData) {
string[] parts=item.split('=');
parts[0] will have the key and parts[1] will have the value. You can now do stuff based on this data.
part[0] 将具有键,parts[1] 将具有值。您现在可以根据这些数据做一些事情。
During the shutdown phase, I do the inverse to write the data back to the list. (Iterate through all the controls in the form and add their settings to ControlData.
在关闭阶段,我执行相反的操作将数据写回列表。(遍历表单中的所有控件并将它们的设置添加到 ControlData。
回答by John
Just in case that still matters to anyone:
以防万一这对任何人都很重要:
You can dynamically add settings through Settings.Default.Properties.Add(...)
and have these also persisted in the local storage after saving (I had those entries reflected in the roaming file).
您可以通过动态添加设置,Settings.Default.Properties.Add(...)
并在保存后将这些设置也保留在本地存储中(我将这些条目反映在漫游文件中)。
Nevertheless it seems that the dynamically added settings keep missing in the Settings.Default.Properties
collecion after loading again.
尽管如此,Settings.Default.Properties
再次加载后,似乎在集合中仍然缺少动态添加的设置。
I could work around this problem by adding the dynamic property before first accessing it. Example (notice that I "create" my dynamic setting from a base setting):
我可以通过在第一次访问之前添加动态属性来解决这个问题。示例(请注意,我从基本设置“创建”了我的动态设置):
// create new setting from a base setting:
var property = new SettingsProperty(Settings.Default.Properties["<baseSetting>"]);
property.Name = "<dynamicSettingName>";
Settings.Default.Properties.Add(property);
// will have the stored value:
var dynamicSetting = Settings.Default["<dynamicSettingName>"];
I don't know if this is supported by Microsoft as the documentation is very rare on this topic.
我不知道这是否受 Microsoft 支持,因为有关此主题的文档非常罕见。
Problem is also described here http://www.vbdotnetforums.com/vb-net-general-discussion/29805-my-settings-run-time-added-properties-dont-save.html#post88152with some solution offered here http://msdn.microsoft.com/en-us/library/saa62613(v=VS.100).aspx(see Community Content - headline "How to Create / Save / Load Dynamic (at Runtime) Settings"). But this is VB.NET.
这里也描述了问题http://www.vbdotnetforums.com/vb-net-general-discussion/29805-my-settings-run-time-added-properties- dont-save.html#post88152 这里提供了一些解决方案http ://msdn.microsoft.com/en-us/library/saa62613(v=VS.100).aspx(请参阅社区内容 - 标题“如何创建/保存/加载动态(在运行时)设置”)。但这是 VB.NET。
回答by Drew Ogle
In addition to John's solution for saving, the proper method for loading is add the property, and then do a Reload() on your settings.
除了 John 的保存解决方案之外,正确的加载方法是添加属性,然后对您的设置执行 Reload()。
Your dynamic setting will be there!
您的动态设置将在那里!
For a full example, valid for using in library code, as you can pass the settings in ..
对于完整示例,可在库代码中使用,因为您可以在 ..
ApplicationSettingsBase settings = passed_in;
SettingsProvider sp = settings.Providers["LocalFileSettingsProvider"];
SettingsProperty p = new SettingsProperty("your_prop_name");
your_class conf = null;
p.PropertyType = typeof( your_class );
p.Attributes.Add(typeof(UserScopedSettingAttribute),new UserScopedSettingAttribute());
p.Provider = sp;
p.SerializeAs = SettingsSerializeAs.Xml;
SettingsPropertyValue v = new SettingsPropertyValue( p );
settings.Properties.Add( p );
settings.Reload();
conf = (your_class)settings["your_prop_name"];
if( conf == null )
{
settings["your_prop_name"] = conf = new your_class();
settings.Save();
}