简体   繁体   中英

create string list in XML settings file

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.

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().

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM