0

what is the best way to save a list of strings to the settings file? i've seen some solutions of editing the xml setting file type to string[], but i can get that to work in the editor.

i also don't know how many strings are going to get added at runtime and it's going to be a lot so i don't want to define a bunch of named strings here. but i still want to save them and have access the next time the application is opened.

i see there is a System.Collections.Specialized.StringCollection in the settings types, is this what i want? if there's a way to save an array to the XML that would work too.

2 Answers 2

1

Here is a simple XML writer script. (untested)

var stringArray = new string[100]; //value of the string
var stringArrayIdentifier = new string[100]; //refers to what you will call the field 
//<identifier>string</identifier>

var settings = new XmlWriterSettings
                   {Indent = true, IndentChars = "\t", NewLineOnAttributes = false};
using (XmlWriter writer = XmlWriter.Create("PATH", settings))
{
    writer.WriteStartDocument();
    foreach (int i = 0; i < stringArray.Length; i++)
    {
        writer.WriteStartElement(stringArrayIdentifier[i]);
        writer.WriteString(stringArray[i]);
        writer.WriteEndElement();
    }
    writer.WriteEndDocument();
}

JavaScriptSerializer.Serialize() will do what you want as well, but with limited use. If all you want is simple, use JavaScriptSerializer.Serialize().

1
  • eh a little more involved than i was hoping. ended up creating one string, separating with a character, and splitting that string into an array later. i know it's not the best idea, but i just needed it to get through haha. i'll try your idea for the next project. Feb 2, 2012 at 6:21
0

Perhaps this question How to store int[] array in application Settings will be of help. Tho if you're looking for a quick and easy way to do it, you could try just serializing the collection to json.

var serializer = new JavaScriptSerializer();
var myArray = new []{"one", "two", "three"};
var myString = serializer.Serialize(myArray);
// Now you can store myString in the settings file...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.