C# File WriteAllLinesAsync() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
System.IO

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.

C#
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);
CallWhat 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
C#
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

ParameterDescription
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 ValueDescription
TaskA task that completes when all lines have been written and the file is closed. There is no result value.

C# Examples

Example 1 — Write a String Array as Lines

Save three fruit names, then read the file back as lines.

C#
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

  1. An array is a sequence. A string[] is an IEnumerable<string>, so it can be passed directly.
  2. One line per string. The method writes apple, banana, and cherry, each followed by a line break.
  3. 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.

C#
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

  1. Five lines first. The first call fills the file with a through e.
  2. A list works too. A List<string> is also an IEnumerable<string>. The second call replaces the file with x and y.
  3. 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.

C#
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

  1. A lazy sequence. Enumerable.Range(1, 3).Select(...) produces Row 1, Row 2, and Row 3 as the method asks for them.
  2. No array needed. WriteAllLinesAsync accepts any IEnumerable<string>, so you do not call ToArray() first.
  3. Check the file. Reading the lines back and joining them with a comma shows Row 1, Row 2, Row 3.

Frequently Asked Questions

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.
Yes. The old content is replaced. Use File.AppendAllLinesAsync to add lines to the end instead.
Any IEnumerable<string>: a string array, a List<string>, or the result of a LINQ query.
Yes. Every line, including the last, is followed by a line break. ReadAllLinesAsync ignores that final break, so the line count stays the same.
UTF-8 without a byte order mark. Pass an Encoding as the third argument to use another one.

Next: WriteAllText()

Save a string to a file in one call, creating it or replacing it.

WriteAllText() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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