C# Program to Append Text to an Existing File

Appending text means adding new information to the end of an existing file. In C#, we can append text to files using various methods from the System.IO namespace. This is particularly useful for logging, data collection, and maintaining records.

Behavior with Non-Existing Files

When attempting to append to a file that doesn't exist, C# automatically creates a new file with the specified name and then adds the content. This eliminates the need for separate file existence checks in most scenarios.

Using File.AppendAllText() Method

Syntax

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

This method opens the specified file, appends the text, and automatically closes the file. It's the simplest approach for adding string content to a file.

Example Appending Simple Text

using System;
using System.IO;

public class Program {
   public static void Main() {
      string filePath = "sample.txt";
      
      // Create initial content
      File.WriteAllText(filePath, "Initial content");
      
      // Append new text
      File.AppendAllText(filePath, Environment.NewLine + "Appended text");
      File.AppendAllText(filePath, Environment.NewLine + "More appended text");
      
      // Read and display the complete file
      string fileContent = File.ReadAllText(filePath);
      Console.WriteLine("Complete file content:");
      Console.WriteLine(fileContent);
   }
}

The output of the above code is

Complete file content:
Initial content
Appended text
More appended text

Example Copying Content from Another File

using System;
using System.IO;

public class Program {
   public static void Main() {
      string sourceFile = "source.txt";
      string targetFile = "target.txt";
      
      // Create source file with sample data
      File.WriteAllText(sourceFile, "Line 1 from source" + Environment.NewLine + "Line 2 from source");
      
      // Create target file with initial content
      File.WriteAllText(targetFile, "Original content" + Environment.NewLine);
      
      // Read content from source and append to target
      string sourceContent = File.ReadAllText(sourceFile);
      File.AppendAllText(targetFile, sourceContent);
      
      // Display the target file content
      string targetContent = File.ReadAllText(targetFile);
      Console.WriteLine("Target file after appending:");
      Console.WriteLine(targetContent);
   }
}

The output of the above code is

Target file after appending:
Original content
Line 1 from source
Line 2 from source

Using File.AppendText() Method

Syntax

public static StreamWriter AppendText(string path);

This method returns a StreamWriter object that allows more control over the appending process. It's useful when you need to append multiple pieces of text or want more granular control.

Example Using StreamWriter for Appending

using System;
using System.IO;

public class Program {
   public static void Main() {
      string filePath = "log.txt";
      
      // Create initial content
      File.WriteAllText(filePath, "Log started" + Environment.NewLine);
      
      // Append multiple lines using StreamWriter
      using (StreamWriter writer = File.AppendText(filePath)) {
         writer.WriteLine("Entry 1: Application started");
         writer.WriteLine("Entry 2: User logged in");
         writer.Write("Entry 3: Process completed");
      }
      
      // Read and display the complete file
      string logContent = File.ReadAllText(filePath);
      Console.WriteLine("Log file content:");
      Console.WriteLine(logContent);
   }
}

The output of the above code is

Log file content:
Log started
Entry 1: Application started
Entry 2: User logged in
Entry 3: Process completed

Using StreamWriter Constructor

You can also use the StreamWriter constructor directly with the append parameter set to true

Example

using System;
using System.IO;

public class Program {
   public static void Main() {
      string filePath = "data.txt";
      
      // Create initial file
      File.WriteAllText(filePath, "Initial data" + Environment.NewLine);
      
      // Append using StreamWriter constructor
      using (StreamWriter writer = new StreamWriter(filePath, true)) {
         writer.WriteLine("Appended line 1");
         writer.WriteLine("Appended line 2");
      }
      
      // Display file contents
      string content = File.ReadAllText(filePath);
      Console.WriteLine("File content:");
      Console.WriteLine(content);
   }
}

The output of the above code is

File content:
Initial data
Appended line 1
Appended line 2

Method Comparison

Method Best Use Case Advantages
File.AppendAllText() Simple text appending Easy to use, automatic file handling
File.AppendText() Multiple append operations Returns StreamWriter for more control
StreamWriter Constructor Custom encoding or buffer size Most flexible approach

Exception Handling

Common exceptions when appending to files include DirectoryNotFoundException when the specified directory doesn't exist, and UnauthorizedAccessException when trying to access read-only files or directories instead of files.

Conclusion

C# provides multiple methods for appending text to files, from the simple File.AppendAllText() for basic scenarios to StreamWriter for more complex operations. Choose the method based on your specific requirements use AppendAllText() for simplicity or StreamWriter when you need more control over the appending process.

Updated on: 2026-03-17T07:04:36+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements