How important is the resulting file to be readable? If this is mostly read later by the program, you should definitely use serialization:
public void SaveArray (string[] array) { NetDataContractSerializer serializer = new NetDataContractSerializer(); using (FileStream file = System.IO.File.Create(_filename)) { serializer.Serialize(file, array); } }
Edit:
To summarize the advantages of this method compared to the other two proposed below, the first uses StringBuilder to concatenate a large string and then save it to disk, and the second using WriteAllLines to write an array of strings to disk:
The first method will completely lose faithfulness to the original list of strings, since it will combine them into one string. Can you split them later? Are there well-known delimiters between them? Not necessary. This is more efficient than just calling + between them, but this is not a very good way to store them.
The second way is better, since each line will be saved on a different line and can be read using ReadAllLines, but you are still on shaky ground. What happens if a line contains a NewLine character? This will be one line when writing, but two different lines when reading. Again, the WriteAllLines / ReadAllLines call relies on newlines that are good delimiters, if not necessary.
Using a serializer - and it doesn't matter if it will be a NetDataContractSerializer, BinaryFormatter or any other - will maintain complete accuracy with your original data structure, with only a bit of overhead.
source share