Appending Lines to Files in C# with `File.AppendAllLines()`: A Simple and Efficient Method

Learn how to use C#'s `File.AppendAllLines()` method to efficiently add lines of text to an existing file. This tutorial explains its functionality, demonstrates its use with various examples, and emphasizes its application in logging and other scenarios requiring data appending to files.



Using C#'s `File.AppendAllLines()` Method

The C# `File.AppendAllLines()` method provides a convenient way to add lines of text to an existing file. This is a common task in many applications, particularly when you need to log information or keep track of events.

Understanding `File.AppendAllLines()`

Unlike `File.WriteAllLines()`, which overwrites the file's content, `File.AppendAllLines()` adds new lines to the end of an existing file. This makes it suitable for situations where you want to maintain a log or append data to a file over time.

`File.AppendAllLines()` Syntax


File.AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding);

The method takes three parameters:

  • path (string): The full path to the file.
  • contents (IEnumerable<string>): A collection of strings (each string will be a new line in the file).
  • encoding (Encoding): The character encoding to use (e.g., `Encoding.UTF8`).

Example: Logging User Activity


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

public class LogExample {
    public static void Main(string[] args) {
        // ... (code to log activities and display log file content) ...
    }
    // ... (LogUserActivity and DisplayLogFile methods) ...
}

Explanation

The `LogUserActivity` method appends user activity messages to the "user_activity.log" file. The `DisplayLogFile` method reads and prints the content. The example uses `Encoding.UTF8` to ensure proper character encoding. Error handling is included to manage the `FileNotFoundException` if the log file doesn't exist.