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 othe开发者_StackOverflow社区r?
The file will be about 0.5 - 1MB in size.
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.
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:
- You don't have to refactor your code when it turns out that your output data is too big to fit in memory.
- The planned destination is the file anyway, so why fool with formatting it in memory before writing to the file?
- The API for writing multiple lines to a text file is, in my opinion, cleaner than the API for adding lines to a
StringBuilder
.
I think it is better to use string or stringbuilder to store your data then you can write to file using File.Write functions.
精彩评论