Home C# File Methods WriteAllLinesAsync() C# File WriteAllLinesAsync() Method Definition In C#, File.WriteAllLinesAsync() creates a file and writes every string of a sequence into it, one per line , then closes the file. An existing file is replaced . It is the async version of File.WriteAllLines().
The lines come from an IEnumerable<string>, so you can pass a string[], a List<string>, or the result of a LINQ query.
It returns a plain Task. Each line is followed by a line break, so the file ends with one too.
Syntax Pass the path and the lines. Add an Encoding to save in something other than UTF-8.
string path = Path.Combine(Path.GetTempPath(), "codetofun-writealllinesasync.txt");
string[] fruits = { "apple", "banana", "cherry" };
await File.WriteAllLinesAsync(path, fruits);
Console.WriteLine((await File.ReadAllLinesAsync(path)).Length); Call What it does await File.WriteAllLinesAsync(path, lines)Writes each string on its own line as UTF-8, replacing the file. await File.WriteAllLinesAsync(path, lines, Encoding.Unicode)Writes with the encoding you name. await File.WriteAllLinesAsync(path, lines, token)Stops with an OperationCanceledException if the token is cancelled.
Use File.AppendAllLinesAsync when you want to add lines to the end of an existing file instead of replacing it.
Library declarations public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, CancellationToken cancellationToken = default);
public static Task WriteAllLinesAsync(string path, IEnumerable<string> contents, Encoding encoding, CancellationToken cancellationToken = default); Parameters Parameter Description pathThe file to write. It is created if missing and replaced if it exists. contentsThe strings to write, one per line. An array, a list, or any IEnumerable<string> works. encodingOptional. The Encoding used to turn the text into bytes. Defaults to UTF-8 without a BOM. cancellationTokenOptional. A token that lets you cancel the write before it finishes.
Return Value Return Value Description TaskA task that completes when all lines have been written and the file is closed. There is no result value.
C# Examples 1. Write an array 2. Replace with a list 3. Write a LINQ sequence Example 1 — Write a String Array as Lines Save three fruit names, then read the file back as lines.
using System;
using System.IO;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-writealllinesasync");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "fruits.txt");
string[] fruits = { "apple", "banana", "cherry" };
await File.WriteAllLinesAsync(path, fruits);
string[] lines = await File.ReadAllLinesAsync(path);
Console.WriteLine(lines.Length);
Console.WriteLine(lines[0]);
Directory.Delete(root, true);
}
} How It Works An array is a sequence. A string[] is an IEnumerable<string>, so it can be passed directly.One line per string. The method writes apple, banana, and cherry, each followed by a line break.Read it back. ReadAllLinesAsync returns three lines, and the first one is apple.Example 2 — Write a List and Replace Older Lines Write five lines, then write two lines to the same file. Only the second write survives.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-writealllinesasync-replace");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "tasks.txt");
await File.WriteAllLinesAsync(path, new[] { "a", "b", "c", "d", "e" });
List<string> shorter = new List<string> { "x", "y" };
await File.WriteAllLinesAsync(path, shorter);
string[] lines = await File.ReadAllLinesAsync(path);
Console.WriteLine(lines.Length);
Console.WriteLine(string.Join(",", lines));
Directory.Delete(root, true);
}
} How It Works Five lines first. The first call fills the file with a through e.A list works too. A List<string> is also an IEnumerable<string>. The second call replaces the file with x and y.Nothing is left over. The file does not keep the old lines. It has exactly two, and string.Join prints x,y.Example 3 — Write Lines Built with LINQ Build the lines on the fly with Enumerable.Range and Select.
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
class Program {
static async Task Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-writealllinesasync-linq");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "rows.txt");
var rows = Enumerable.Range(1, 3).Select(i => "Row " + i);
await File.WriteAllLinesAsync(path, rows);
string[] lines = await File.ReadAllLinesAsync(path);
Console.WriteLine(string.Join(", ", lines));
Directory.Delete(root, true);
}
} How It Works A lazy sequence. Enumerable.Range(1, 3).Select(...) produces Row 1, Row 2, and Row 3 as the method asks for them.No array needed. WriteAllLinesAsync accepts any IEnumerable<string>, so you do not call ToArray() first.Check the file. Reading the lines back and joining them with a comma shows Row 1, Row 2, Row 3.Frequently Asked Questions What does File.WriteAllLinesAsync do? It writes each string of a sequence to a file, one per line, then closes the file. It replaces an existing file and returns a Task.
Does WriteAllLinesAsync overwrite an existing file? Yes. The old content is replaced. Use File.AppendAllLinesAsync to add lines to the end instead.
What can I pass as the lines? Any IEnumerable<string>: a string array, a List<string>, or the result of a LINQ query.
Does the last line end with a line break? Yes. Every line, including the last, is followed by a line break. ReadAllLinesAsync ignores that final break, so the line count stays the same.
What encoding does WriteAllLinesAsync use? UTF-8 without a byte order mark. Pass an Encoding as the third argument to use another one.
CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
13 people found this page helpful
Helpful Share Copy link Suggestion