- C# Write Text Files
- Writing all text into a text file
- Writing one or more strings into a text file
- Writing into a text file using StreamWriter
- Writing into a text file asynchronously
- Summary
- How to: Write text to a file
- Example: Synchronously write text with StreamWriter
- Example: Synchronously append text with StreamWriter
- Example: Asynchronously write text with StreamWriter
- Example: Write and append text with the File class
- See also
- Feedback
C# Write Text Files
Summary: in this tutorial, you’ll learn various techniques to write text files in C# using the File static methods and StreamWriter class.
Writing all text into a text file
The File.WriteAllText () method creates a new file, writes the contents to it, and then closes the file:
public static void WriteAllText (string path, string? contents);
Code language: C# (cs)
If the file specified by the path exists, the WriteAllText() method overwrites it. In other words, the contents of the existing file will be replaced by the contents.
The following program demonstrates how to use File.WriteAllText () method to write all text into a text file:
using static System.Console; string path = @"C:\temp\readme.txt"; string contents = "Hello\nGoodbye"; File.WriteAllText(path, contents);
Code language: C# (cs)
The readme.txt will look like the following:
Hello Goodbye
Code language: C# (cs)
This program writes the string “Hello” and “Goodbye” to the readme.txt file located in the “C:\temp” directory.
If the C:\temp directory does not exist, the WriteAllText() method throws a DirectoryNotFoundException .
For example, the following program attempts to write text to a file readme.txt located in the C:\temp1 directory. Since the directory C:\temp1 doesn’t exist, the program shows a message provided by the DirectoryNotFoundException object:
using static System.Console; string path = @"C:\temp1\readme.txt"; string contents = "Hello\nGoodbye"; try < File.WriteAllText(path, contents); >catch (DirectoryNotFoundException e) Code language: C# (cs)
Could not find a part of the path 'C:\temp1\readme.txt'.
Code language: C# (cs)
To check if the text file exists before writing the contents to it, you can use the File.Exists () method like this:
using static System.Console; string path = @"C:\temp\readme.txt"; string contents = "Hello\nGoodbye"; if (!File.Exists(path)) < File.WriteAllText(path, contents); >else < WriteLine($"The file alrady exists"); >
Code language: C# (cs)
The file C:\temp\readme.txt alrady exists
Code language: C# (cs)
Writing one or more strings into a text file
To write one or more strings into a text file, you use the File.WriteAllLines () method. The File.WriteAllLines () method creates a new file, writes one or more strings to the file, and then closes the file:
public static void WriteAllLines ( string path, string[] contents );
Code language: C# (cs)
string path = @"C:\temp\readme.txt"; string[] lines = new[] < "Hello", "Hi", "Hey" >; File.WriteAllLines(path, lines);
Code language: C# (cs)
The readme.txt file will look like this:
Hello Hi Hey
Code language: C# (cs)
Writing into a text file using StreamWriter
When you have a large amount of text data that you want to write into a text file in sequential order, you can use StreamWriter . For example:
string path = @"C:\temp\readme.txt"; // in practice, the greetings is very big string[] greetings = new[] < "Hello", "Hi", "Hey" >; var fs = new FileStream(path, FileMode.Open); var stream = new StreamWriter(fs); foreach (var greeting in greetings) < // write each line to the stream stream.WriteLine(greeting); >
Code language: C# (cs)
First, define a string variable named “path” and assigns it the value of the file path C:\temp\ readme.txt where we want to write the text.
Next, create an array of strings named “greetings” that has three different strings – «Hello», «Hi» , and «Hey» .
Then, create a FileStream object named fs that open the file specified by the path with the mode FileMode .Open.
After that, create a StreamWriter object that writes text to the file using the FileStream object.
Finally, iterate the greetings array and write each element into the file using the StreamWriter object.
Writing into a text file asynchronously
To write data into a text file asynchronously, you can use the async versions of the WriteAllText and WriteAllLines() methods:
public static Task WriteAllTextAsync (string path, string? contents, CancellationToken cancellationToken = default); public static Task WriteAllLinesAsync (string path, IEnumerablestring> contents, CancellationToken cancellationToken = default)
;Code language: C# (cs)
string path = @"C:\temp\readme.txt"; string[] greetings = new[] < "Hello", "Hi", "Hey" >; await File.WriteAllLinesAsync(path, greetings);
Code language: C# (cs)
In this example, we use the WriteAllLinesAsync() method to asynchronously write the array of strings into a text file.
Note that we use the await keyword to wait for the WriteAllLinesAsync() method to complete.
Summary
- Use the File.WriteAllText () method to write all text into a text file.
- Use the File.WriteAllTextAsync () method to write text data into a text file asynchronously.
- Use the File.WriteAllLines () method to write an array of strings into a text file.
- Use the File.WriteAllLinesAsync () method to write an array of strings into a text file asynchronously.
- Use the StreamWriter to write a large amount of text into a text file.
How to: Write text to a file
This article shows different ways to write text to a file for a .NET app.
The following classes and methods are typically used to write text to a file:
- StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync).
- File provides static methods to write text to a file such as WriteAllLines and WriteAllText, or to append text to a file such as AppendAllLines, AppendAllText, and AppendText.
- Path is for strings that have file or directory path information. It contains the Combine method and in .NET Core 2.1 and later, the Join and TryJoin methods. These methods let you concatenate strings for building a file or directory path.
The following examples show only the minimum amount of code needed. A real-world app usually provides more robust error checking and exception handling.
Example: Synchronously write text with StreamWriter
The following example shows how to use the StreamWriter class to synchronously write text to a new file one line at a time. Because the StreamWriter object is declared and instantiated in a using statement, the Dispose method is invoked, which automatically flushes and closes the stream.
using System; using System.IO; class Program < static void Main(string[] args) < // Create a string array with the lines of text string[] lines = < "First line", "Second line", "Third line" >; // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Write the string array to a new file named "WriteLines.txt". using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"))) < foreach (string line in lines) outputFile.WriteLine(line); >> > // The example creates a file named "WriteLines.txt" with the following contents: // First line // Second line // Third line
Imports System.IO Class WriteText Public Shared Sub Main() ' Create a string array with the lines of text Dim lines() As String = ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Write the string array to a new file named "WriteLines.txt". Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt"))) For Each line As String In lines outputFile.WriteLine(line) Next End Using End Sub End Class ' The example creates a file named "WriteLines.txt" with the following contents: ' First line ' Second line ' Third line
Example: Synchronously append text with StreamWriter
The following example shows how to use the StreamWriter class to synchronously append text to the text file created in the first example:
using System; using System.IO; class Program < static void Main(string[] args) < // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Append text to an existing file named "WriteLines.txt". using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) < outputFile.WriteLine("Fourth Line"); >> > // The example adds the following line to the contents of "WriteLines.txt": // Fourth Line
Imports System.IO Class AppendText Public Shared Sub Main() ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Append text to an existing file named "WriteLines.txt". Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")), True) outputFile.WriteLine("Fourth Line") End Using End Sub End Class ' The example adds the following line to the contents of "WriteLines.txt": ' Fourth Line
Example: Asynchronously write text with StreamWriter
The following example shows how to asynchronously write text to a new file using the StreamWriter class. To invoke the WriteAsync method, the method call must be within an async method.
using System; using System.IO; using System.Threading.Tasks; class Program < static async Task Main() < // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Write the specified text asynchronously to a new file named "WriteTextAsync.txt". using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteTextAsync.txt"))) < await outputFile.WriteAsync("This is a sentence."); >> > // The example creates a file named "WriteTextAsync.txt" with the following contents: // This is a sentence.
Imports System.IO Public Module Example Public Sub Main() WriteTextAsync() End Sub Async Sub WriteTextAsync() ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Write the text asynchronously to a new file named "WriteTextAsync.txt". Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteTextAsync.txt"))) Await outputFile.WriteAsync("This is a sentence.") End Using End Sub End Module ' The example creates a file named "WriteTextAsync.txt" with the following contents: ' This is a sentence.
Example: Write and append text with the File class
The following example shows how to write text to a new file and append new lines of text to the same file using the File class. The WriteAllText and AppendAllLines methods open and close the file automatically. If the path you provide to the WriteAllText method already exists, the file is overwritten.
using System; using System.IO; class Program < static void Main(string[] args) < // Create a string with a line of text. string text = "First line" + Environment.NewLine; // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Write the text to a new file named "WriteFile.txt". File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text); // Create a string array with the additional lines of text string[] lines = < "New line 1", "New line 2" >; // Append new lines of text to the file File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines); > > // The example creates a file named "WriteFile.txt" with the contents: // First line // And then appends the following contents: // New line 1 // New line 2
Imports System.IO Class WriteFile Public Shared Sub Main() ' Create a string array with the lines of text Dim text As String = "First line" & Environment.NewLine ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Write the text to a new file named "WriteFile.txt". File.WriteAllText(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), text) ' Create a string array with the additional lines of text Dim lines() As String = ' Append new lines of text to the file File.AppendAllLines(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), lines) End Sub End Class ' The example creates a file named "WriteFile.txt" with the following contents: ' First line ' And then appends the following contents: ' New line 1 ' New line 2
See also
Feedback
Submit and view feedback for