C# can open a file for reading and writing (r+) or writing (w+). This is for files on the hard disk, not on the cloud.

In this article we will cover how to write files in c#. If you are interested in reading files, see tthe read-file article instead.

Write files in C#

Write file

The c# program below writes a file from the disk. If the file exists, it will be overwritten (w+). If you want to add to end of the file instead, use (a+).

1
2
3
4
5
6
// No w+ in C#, rewrite article!

using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}

This writes the c# string into the newly created file. If you get an error, it means you don’t have the right user permissions to write a file (no write access) or that the disk is full.

Otherwise the new file has been created (file.txt). This file contains the string contents which you can see with any text editor.

Flags

If you use the w+ flag the file will be created if it doesn’t exist. The w+ flag makes c# overwrite the file if it already exists.

The r+ does the same, but csharp then allows you to read files. Reading files is not allowed with the w+ flag.

If you want to append to a file (add) you can use the a+ flag. This will not overwrite the file, only append the end of the file.

Exercises

  1. Write a list of cities to a new file.