Should I create a string first and then write to a file?

The program I'm working on right now should generate a file. Is it better for me to first generate the contents of the file as a string and then write this string to the file or just add the contents to the file?

Are there any advantages of one over the other?

The file size will be about 0.5 - 1 MB.

+3
source share
3 answers

If you write the file as-you-go, it will be useful for you not to store everything in memory if it is a large enough file and you constantly clear the stream.

However, you will be more likely to encounter problems with a partially written file, since you are doing your IO for a certain period of time, and not at a time.

StringBuilder, .

+9

, StreamWriter . , ? . :

using (var writer = new StreamWriter("filename"))
{
    writer.WriteLine(header);
    // write all your data with Write and WriteLine,
    // taking advantage of composite formatting
}

StringBuilder, - :

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

, . List<string>, File.WriteAllLines. StringStream, . . StreamWriter .

, , :

  • , , , .
  • - , ?
  • API , , , API StringBuilder.
+2

I think it is better to use string or stringbuilder to store your data, then you can write them to a file using the File.Write functions.

-1
source

Source: https://habr.com/ru/post/1795765/


All Articles