问题
For my latest WPF application, I've been using an System.Collections.Specialized.StringCollection
to save and load strings. My current system works like a charm in Debug and Release, but when deployed to ClickOnce, the application crashes as soon as anything involving the settings are involved (loading or saving)! However, System.Collections.Specialized.StringCollections
work just fine on their own if not a setting.
What could be causing these crashes?
Here are my systems:
public static void SaveCharacter(string code)
{
// Declare a blank StringCollection
StringCollection strings = new StringCollection();
// Convert the current settings StringCollection into an array and combine with the blank one
if (Settings.Default.SavedCharacters.Count > 0)
{
string[] tempArr= new string[Settings.Default.SavedCharacters.Count];
Settings.Default.SavedCharacters.CopyTo(tempArr, 0);
strings.AddRange(tempArr);
}
// Add the new string to the list
strings.Add(code);
// This new list is now saved as the setting itself
Settings.Default.SavedCharacters = strings;
Settings.Default.Save();
}
public static void RestoreCharacters()
{
foreach (string str in Settings.Default.SavedCharacters)
{
CreateCharacter(str, "l" + ID.ToString()); // This function works fine
ID++; // So does this variable (it's a public static)
}
}
P.S. I tried a similar system with List<string>
items, but no dice. Other settings involving strings
, bools
and ints
work fine though.
P.P.S. Sidenote, does anyone know how to combine System.Collections.Specialized.StringCollections
without having to convert one to an array?
回答1:
Answering my own question in case anyone else gets stuck with such an annoying bug! Before you can operate on a User Setting that has to be newed()
, you need to create an instance of it to utilise instead. For example:
StringCollection foo = Settings.Default.SavedCharacters;
When it comes to saving such collections, simply using Settings.Default.SavedCharacters = foo;
works fine!
来源:https://stackoverflow.com/questions/59222317/system-collections-specialized-stringcollection-settings-work-fine-in-debug-and