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