TOC

The community is working on translating this tutorial into Greek, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

File handling:

Reading and writing files

In this chapter, we will look into reading and writing simple files with C#. Fortunately for us, C# makes it very easy. The File class, from the Syste.IO namespace comes with pretty much everything we could possibly want, making it very easy to do simple reading and writing of a file.

In our first example, we will construct an extremely minimalistic text editor. In fact, it is so simple that we can only read one file and then write new content to it, and only a single line of text at a time. But it shows just how easy it is to use the File class:

using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if(File.Exists("test.txt"))
            {
                string content = File.ReadAllText("test.txt");
                Console.WriteLine("Current content of file:");
                Console.WriteLine(content);
            }
            Console.WriteLine("Please enter new content for the file:");
            string newContent = Console.ReadLine();
            File.WriteAllText("test.txt", newContent);
        }
    }
}

You will notice that we use the File class in three places: We use it to check if our file exists, we use the ReadAllText() method to read the content of the file, and we use the WriteAllText() method to write new content to the file. You will notice that I'm not using absolute paths, but just a simple filename. This will place the file in the same directory as the executable file, which is fine for now. Other than that, the example should be easy enough to understand: We check for the file, if it exists, we read its content and output it to the console. Then we prompt the user for new content, and once we have it, we write it to the file. Obviously that will overwrite the previous content, but for now, that's just fine. We could however use the AppendAllText method instead. Try changing the WriteAllText line to this instead:

File.AppendAllText("test.txt", newContent);

If you run it, you will see that the new text is added to the existing text instead of overwriting it. As simple as that. But we still get only one line of text per execution of our application. Let's be a bit creative and change that. Replace the last lines in our example with this:

Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
string newContent = Console.ReadLine();
while(newContent != "exit")
{
    File.AppendAllText("test.txt", newContent + Environment.NewLine);
    newContent = Console.ReadLine();
}

As you can see, we instruct the user to enter the word exit when they wish to stop editing the file, and until they do just that, we append the user input to the file and then prompt for a new line. We also append a newline character, the Environment.NewLine, to make it look like actual lines of text.

However, instead of writing to the file each time, a more pretty solution would probably look something like this:

Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
using(StreamWriter sw = new StreamWriter("test.txt"))
{
    string newContent = Console.ReadLine();
    while(newContent != "exit")
    {
        sw.Write(newContent + Environment.NewLine);
        newContent = Console.ReadLine();
    }
}

The usage of Streams is a bit out of the scope of this chapter, but the cool thing about it in this example is that we only open the file once, and then write the changes to it once we're satisfied. In this case, we're taking advantage of the using() statement of C#, which ensures that the file reference is closed once it goes out of scope, which is when it's block of { } is done. If you don't use the using() statement, you will have to manually call the Close() method on the StreamWriter instance.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!