C# Program to Append Text to an Existing File


Introduction

Append means adding information to the already written document. Here, we will be learning to write a C# program to append text to an existing file. As we know file handling is done in C#. In most cases, the file is used to store data. File handling or file management in layman’s terms the various processes such as making the file, reading from it, writing to it, appending it, and so on.

Only to Existing Files?

Well, as we know appending generally means adding a piece of information to the already written document. But what if the file we are trying to access is a file that does not exist? Suppose we are searching for a file named 'madrid.txt' for appending it. If the file is existing in the specified directory then the file is appended. But what if the file 'madrid.txt' does not exist? Then, the program creates a new file named 'madrid.txt' in which you can add the information. So, when we try to open a file in append mode then if that specific file does not exist then a new empty file with the name of the file we want to append is created.

1. File.AppendAllText(String, String) Method

File.AppendAllText() method is a very common solution to our problem of appending to an existing file. This method is from the File class. The syntax of this method is as follows.

public static void AppendAllText (string path, string? contents); 

In syntax, the first string contains the path of the file that we intend to append. After that, the information that we want to add to the file is followed. This can throw a couple of exceptions too. This throws DriectoryNotFoundException if the directory we are trying to access for the file does not exist. Another majorly thrown exception is UnauthorizedAccessException. This happens when the programmer trying to access a file is a read-only file or the path specified points to a directory and not to a file.

The file handle will be closed when this method is used irrespective of the exceptions thrown.

Algorithm

Now, we will discuss the algorithm for creating a program to use File.AppendAllText() for adding the information to the file.

Step 1 − Firstly, we create a string to store the address of the file to append and then provide the address of the file.

Step 2 − Then we use the FileAppendAllText() which opens the file in append mode and adds the specific text to the file. If that file does not exist then a new file is created with that name and the text is added.

Step 3 − Finally, the text is read from the file so that we can see that the file is appended and then the program exits.

Example

// A program to append the file
using System;
using System.IO;

public class Program {
   public static void Main() {
      string loca = @"D:\madrid.txt";

      // Adding the text to the madrid.txt file
      File.AppendAllText(loca, Environment.NewLine + "UCL");

      // Reading the text from the madrid.txt file
      string txtappd = File.ReadAllText(loca);
      Console.WriteLine(txtappd);
   }
}

Output

UCL

So, the path of the file is provided and then this method opens the specified file, adds the piece of desired information of the programmer, and then closes the file. Very simple, but what if we want to copy the entire content from a file to our desired file? Yes, this method also solves our copying of file problem. Now it is time to discuss Algorithms.

Algorithm

This algorithm is about using File.AppendAllText().

Step 1 − A string to store the address of the source file is created.

Step 2 − Another string is created to store the address of the destination file.

Step 3 − File.Readlines() is used to copy the source file in a string.

Step 4 − The file is opened in append mode by File.AppendAllText(). Then the text is added.

Step 5 − Program exits after completion.

Example

// A program to append the file
using System;
using System.Collections.Generic;
using System.IO;

public class Program {
   public static void Main() {
      string sttr1 = @"D:\trophies.txt";
      string sttr2 = @"D:\madrid.txt";

      // Copying all the text from the source file in a string and then adding to the destination file
      IEnumerable<string> inform = File.ReadLines(sttr1);
      File.AppendAllLines(sttr2, inform);
   }
} 

Now let’s see one more way to do so.

2. File.AppendText() Method

SteamWriter class is a very versatile class. It provides a lot of methods for writing in a file. WriteLine() or Write() are the different methods that can be used to add text to the stream.

public static System.IO.StreamWriter AppendText (string path); 

A StreamWriter instance can be created by using File.AppendAllText() method which appends text to the existing file in UTF-8 encoding. It also creates a new file if that specified file does not exist.

This throws DriectoryNotFoundException if the directory we are trying to access for the file does not exist. Another majorly thrown exception is UnauthorizedAccessException. This happens when the programmer trying to access a file is a read-only file or the path specified points to a directory and not to a file.

Algorithm

Now, we will discuss the algorithm for creating a program to use File.AppendText() for adding the information to the file.

Step 1 − Firstly, we create a string to store the address of the file to append and then provide the address of the file.

Step 2 − Now, we create an instance of StreamReader. This step opens the file in append mode and adds text to the file. We use File.AppendText() for adding text.

StreamReader.Write() method is used for appending. If the user wants to append the text and then add a line terminator at the end. StreamReader.WriteLine() method is used.

Step 3 − Program exits after completion.

Example

// A program to append the file
using System;
using System.IO;

public class Program {
   public static void Main() {
      string loca = @"D:\madrid.txt";

      // Adding the text to the specified file
      using (StreamWriter sw = File.AppendText(loca)) {
         sw.Write("UCL"); //use sw.WriteLine(If you want to add line termination)
      }

      // Read the text from the appended file
      string txtappd = File.ReadAllText(loca);
      Console.WriteLine(txtappd);
   }
}

Output

UCL

StreamWriter(String, Boolean) the constructor overloaded version is also equivalent to File.AppendText(). Whereas for the Boolean parameter, we use true.

Algorithm for StreanWriter(String, Boolean)

Now, we will discuss the algorithm for creating a program to use StreamWriter(String, Boolean) for adding the information to the file.

Step 1 − Firstly, we create a string to store the address of the file to append and then provide the address of the file

Step 2  Now, we create an instance of StreamReader. This step opens the file in append mode and adds text to the file. We use the new Streamwriter() for adding the information. Here, we are using StreamReader.Write() method for appending. But if we need to append the text and then add a line terminator at the end then we can use StreamReader.WriteLine() method.

Step 3  Finally, the text is read from the file so that we can see that the file is appended and then the program exits.

Example

// A program to append the file
using System;
using System.IO;

public class Program {
   public static void Main() {
      string loca = @"D:\madrid.txt";

      // Adding the text to the specified file
      using (StreamWriter sw = new StreamWriter(loca, true)) {
         sw.Write("UCL"); //use sw.WriteLine(If you want to add line termination)
      }

      // Read the text from the appended file
      string txtappd = File.ReadAllText(loca);
      Console.WriteLine(txtappd);
   } 
}

Output

UCL

Time Complexity

Since here in both processes, we are using file handling. Here in the first algorithm, we are using File.AppendAllText() and in the second one we have used File.AppendText() and both of them are just appending the files. They are taking the new text and adding it to the end of the file. So, here the time complexity of both methods stands to be O(1).

Conclusion

In this article, we have discussed different ways to append text to an existing file. Firstly we discussed the need and whether can it be done only to existing files. Then we discussed the methods of appending File.AppendAllText() and File.AppendText(). Finally, we discussed the algorithm and the code for the algorithm.

We hope that this article has helped you enhance your knowledge regarding C#.

Updated on: 14-Jul-2023

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements