问题
I would like to use a StringCollection as application settings, however while reading it's not a problem, I found out that settings are not stored.
How to make it works? Any workaround? What's the problem here?
Code I'm using:
private static void AddToRecentProfiles(string path)
{
if (SpellCaster3.Properties.Settings.Default.RecentProfiles == null)
SpellCaster3.Properties.Settings.Default.RecentProfiles = new StringCollection();
int index = SpellCaster3.Properties.Settings.Default.RecentProfiles.IndexOf(path);
if (index >= 0)
SpellCaster3.Properties.Settings.Default.RecentProfiles.Swap(index, 0);
else
SpellCaster3.Properties.Settings.Default.RecentProfiles.Insert(0, path);
if (SpellCaster3.Properties.Settings.Default.RecentProfiles.Count > SpellCaster3.Properties.Settings.Default.MaxRecentProfiles)
SpellCaster3.Properties.Settings.Default.RecentProfiles.RemoveAt(SpellCaster3.Properties.Settings.Default.RecentProfiles.Count - 1);
SpellCaster3.Properties.Settings.Default.Save();
OnRecentProfilesChanged(SpellCaster3.Properties.Settings.Default.RecentProfiles, EventArgs.Empty);
}
回答1:
I found the solution by myself, the problem is that if you create your StringCollection with "new" keyword and save settings, they don't get stored.
The way to fix this is to "force" the application settings designer to create it for you, how to do it? Well it's quite easy, put stringcollection as type and insert 2/3 strings. Press ok. Then edit again this value and remove all strings to leave it "created but empty".
After this, you can just use it by adding/removing strings and save settings. And you will be sure it won't be null!
回答2:
Application settings can be scoped at the application level and at the user level and you can only write to settings at the user level, so if you have a StringCollection
scoped at the application level you can only read the values that you defined at compile time and adding to the collection at runtime will have no effect the next time you start your application.
You can scope it at the user level if you want changes to propagate between application runs.
来源:https://stackoverflow.com/questions/6557338/stringcollection-in-application-settings-doesnt-get-stored