Write to Text File C#

USE STREAMWRITER TO WRITE TO A FILE IN C#

by

To write to a text file in C#, you will use a StreamWriter object. In this tutorial, you will learn how to use StreamWriter to write a string to a file synchronously. You can also use StreamWriter to append text to an existing file and to write to a file asynchronously.

Using StreamWriter to Write to a File

To use the StreamWriter object, you must include the System.IO directive in your project.

using System;
using System.IO;

To create an instance of a StreamWriter object, you must define the location and filename of the file you wish to write. Once the object is instantiated, you can use it to write content to the file.

static void Main(string[] args)
{
    string filePath = @"C:\Users\wellsb\Desktop\WriteFile.txt";
 
    string content = "Free C# tutorials at wellsb.com";
 
    using (StreamWriter outputFile = new StreamWriter(filePath))
    {
        outputFile.WriteLine(content);
    }
}

On Line 10, we have declared the path to the file we wish to write to. If the file does not exist, the StreamWriter object will create it. Note, if you include only a filename ("WriteFile.txt") and not a full directory path, the file will be written in the project folder.

You can also use your system's environment variables to dynamically reference known folders. The following snippet is a better way to write Line 10 above, because the code becomes compatible across different machines.

string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "WriteFile.txt");

On Line 14, the StreamWriter object is initiated. By passing the filePath variable as an argument to the StreamWriter class, StreamWriter will create and write to the file in that location. Note the use of the using statement on Line 14. The using keyword ensures that the Dispose() method of the referenced object is called, even if an exception occurs. In this case, it properly disposes of the StreamWriter object once the file write operation is complete.

Line 16 will write the string Free C# tutorials at wellsb.com (declared on Line 12) to the file specified on Line 10. This examples uses the WriteLine() method, but the StreamWriter class also includes a Write() method that will not include a newline character. These are similar to the Write() and WriteLine() methods of the Console class.

Append Text to Existing File

The default action for the StreamWriter class is to overwrite the contents of the file when it already exists. The way we have declared the StreamWriter object on Line 14 above will do just that. Fortunately, the .NET Framework includes a number of constructors for the StreamWriter class, and one of these allows us to append to the file instead.

To append, that is to say to write a string to the end of the file, is as simple as passing a second argument to the constructor. The second argument will be a bool variable. Passing true will append to the file.

using (StreamWriter outputFile = new StreamWriter(filePath, true))

The Bottom Line

In this tutorial, you learned how to use a StreamWriter object to write a string to a text file. This could be useful if you wish to create a settings file on the disk, for example. Note, this method is for writing to a file synchronously. Your program will not execute any other code until the contents of the file are written. The StreamWriter class can also be used to write to a file asynchronously. This will be the subject of the next tutorial.


Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.


Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets