Reputation: 42450
A program I am working on right now has to generate a file. Is it better for me to generate the file's contents as a string first and then write that string to the file, or should I just directly add the contents to the file?
Are there any advantages of one over the other?
The file will be about 0.5 - 1MB in size.
Upvotes: 3
Views: 270
Reputation: 133995
I think it's a better idea, in general, to create a StreamWriter
and just write to it. Why keep things in memory when you don't have to? And it's a whole lot easier. For example:
using (var writer = new StreamWriter("filename"))
{
writer.WriteLine(header);
// write all your data with Write and WriteLine,
// taking advantage of composite formatting
}
If you want to build multiple lines with StringBuilder
you have to write something like:
var sb = new StringBuilder();
sb.AppendLine(string.Format("{0:N0} blocks read", blocksRead));
// etc., etc.
// and finally write it to file
File.WriteAllText("filename", sb.ToString());
There are other options, of course. You could build the lines into a List<string>
and then use File.WriteAllLines
. Or you could write to a StringStream
and then write that to the file. But all of those approaches have you handling the data multiple times. Just open the StreamWriter
and write.
The primary reasons I think it's a better idea in general to go directly to output:
StringBuilder
.Upvotes: 2
Reputation: 550
I think it is better to use string or stringbuilder to store your data then you can write to file using File.Write functions.
Upvotes: -1
Reputation: 44632
If you write to a file as-you-go, you'll have the benefit of not keeping everything in memory, if it's a big enough file and you constantly flush the stream.
However, you'll be more likely to run into problems with a partially-written file, since you're doing your IO over a period of time instead of in a single shot.
Personally, I'd build it up using a StringBuilder, and then write it all to disk in a single shot.
Upvotes: 9