Text files in C#

Text files is an important topic to master in programming. In this post, you will learn how to use text files in C#.

Why do we need files in programming?

A computer can store data in two ways:

An example of the use of RAM to store data is in programming when you create an integer variable and assign a number to it. In this case, the value you assigned to the variable is stored in RAM. This way of storing data is very efficient. However, if you restart the computer, the data will be lost.

So, how do we store data more permanently?

Your guess is right, using computer files.

Once you store data on a computer file, the data will be there if you restart your computer. The only way to lose that data is if you delete the file, or the hard drive fails.

You can read more about some applications at this link.

Important concepts to know when using files

There are just a few concepts we need to consider when using files.

The first one is the type of file. Files can be binary or text-based files. In this post, I’m going to focus on text files. The type of the file determines which classes you need to use, and how the information is stored.

Text files are stored as plain text. This means if you open a text file, you will see the same text you wrote to the file. On the other hand, if you open a binary file, you won’t understand what you will see.

The second thing to understand is that anytime we work with files, several types of exceptions can occur. So, every time we do something with a file, we need to use exception handling.

Finally, we need to close the file always. If we open a file and we don’t close it before exiting the program, it can lead to inconsistencies in the file and can make it unusable. Leading to loss of data.

Type of exceptions that can occur when using files

See below a list of exceptions that can occur when we use files in our code.

The base class for most input/output exceptions is IOException. It is always recommended to use a specific type of exception so we can give a more helpful message to the users when an exception occurs.

Create a text file

Verbatim string literals are more convenient for multi-line strings, strings that contain backslash characters, or embedded double quotes.” Source. Because of this, you should use Verbatim string literals for the file name when using the whole path in Windows.

An example of this type of string is:

string path = @"C:\temp\textfile.txt";

Creating a file.

string path = "file.txt";
if (!File.Exists(path))
{
     File.CreateText(path);
}

File.CreateText creates a new file in the specified path. If the file already exists, it is overridden. In other words, if you this method and the file already exists, you will lose the information that is in the file. That is why it is always a good idea to ask if the file exists before using this method.

Write to a text file

To write to a text file, we can use the class StreamWriter. But first, we need to open the file. See the example below.

StreamWriter sw = File.CreateText(path)

After the file is open, we can write to the file using the method WriteLine.

sw.WriteLine("Hello");

See the whole example below.

           string path = "file.txt";
            if (!File.Exists(path))
            {
                // If the file does not exist, create it
                StreamWriter sw = null;
                try
                {
                    sw = File.CreateText(path);
                    //Write something to the file
                    sw.WriteLine("Hello World");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally {
                    sw.Close();
                }
            }

After executing this code, you can open the file that was created, and you will see the following.

text file example 1
Text file example 1

As you can see, the content in the file is the string “Hello World”.

Sometimes, we need to open a file that already exists and add more data. When that happens, if the file already exists, we need to open it in another mode called “append” in several programming languages.

Find the example below.

            string path = "file.txt";
            StreamWriter sw = null;
            if (!File.Exists(path))
            {
                // If the file does not exist, create it
                try
                {
                    sw = File.CreateText(path);
                    //Write something to the file
                    sw.WriteLine("Hello World");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sw.Close();
                }
            }
            else {
                try
                {
                    sw = File.AppendText(path);
                    //Write something to the file
                    sw.WriteLine("Appending a second line");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sw.Close();
                }
            }

After executing this code, you will see the following output if you open the text file.

text file example 2
Text file example 2

Read text file line by line

There is a structure in C# that warrantee to close the file whether an exception occurs or not. This means you won’t need to use a try-catch block in the method you are reading or writing to a file.

However, notice that you will need the try-catch block to give useful information to the user in the case of an error. For instance, if the user is trying to access a file and doesn’t have enough permissions. In this case, you want to tell the user what is happening.

          string path = "file.txt";
            using (StreamReader sr = File.OpenText(path)) {
                while (!sr.EndOfStream) {
                    Console.WriteLine(sr.ReadLine());
                }
            }

Read the whole text file

You can also read a text file in one line using the following code.

string path = "file.txt";
string text = File.ReadAllText(path);

Console.WriteLine(text);

If you execute the two last examples, you will get the same output.

text file example 3
Text file example 3

H@ppy coding!