Other

C# write to file: picking between WriteAllText, AppendAllText and StreamWriter

Khalid Abuhakmeh Khalid Abuhakmeh
Other

A hands-on reference for writing files in C#: which System.IO method to pick for text, lines, bytes, appends and streaming, plus the async variants and the folder trap that breaks WriteAllText.

Key points

  • File.WriteAllText creates or overwrites a file and closes it, using UTF-8 without BOM by default.
  • WriteAllLines accepts a string[] or any IEnumerable<string> and emits the platform newline between entries.
  • AppendAllText and AppendAllLines add to existing content but add no newline on their own.
  • No WriteAll* method creates missing folders; call Directory.CreateDirectory first to avoid DirectoryNotFoundException.
  • StreamWriter suits large or incremental output and takes append: true; use await using with WriteLineAsync in async code.
  • Every WriteAll* and AppendAll* method has an async counterpart accepting an optional CancellationToken.

This summary was generated by the agent from the original post on Khalid Abuhakmeh. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message