To append new line data to the end of an existing text file, use the System.IO.File.AppendAllLines method. This method automatically creates a new file if the specified file does not exist. If the file already exists, it writes the data starting from the end of the original file without deleting existing data.
目次
Table of Contents
- Implementation Sample: Appending Log Data
- Sample Code
- Execution Result (Case where the file was initially empty)
- Explanation
- Features of File.AppendAllLines
Implementation Sample: Appending Log Data
The following code appends new log information to a file (operation.log) used to record operation logs.
Sample Code
using System;
using System.IO;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Data to append (string array)
string[] newLogs = new string[]
{
"[2025-01-07 14:00] Server connection started",
"[2025-01-07 14:01] Data synchronization completed",
"[2025-01-07 14:02] Process finished"
};
// Target file path
string filePath = "operation.log";
try
{
Console.WriteLine("Appending logs...");
// File.AppendAllLines(file path, data to add)
// Appends each element of the array as a new line to the end of the file
File.AppendAllLines(filePath, newLogs);
Console.WriteLine("Append completed.");
// (For confirmation) Display all file contents
Console.WriteLine("\n--- Current file content ---");
string currentContent = File.ReadAllText(filePath);
Console.WriteLine(currentContent);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Execution Result (Case where the file was initially empty)
Appending logs...
Append completed.
--- Current file content ---
[2025-01-07 14:00] Server connection started
[2025-01-07 14:01] Data synchronization completed
[2025-01-07 14:02] Process finished
If you run this program again, the same content will be appended further down.
Explanation
Features of File.AppendAllLines
- Automatic Line Breaks: It automatically inserts a line break between each element of the passed collection (array or List). You do not need to manually concatenate
\n. - Behavior when the file is missing: If no file exists at the specified path, it does not cause an error; instead, it creates a new file and writes the data.
- Argument Types: For the second argument, you can pass not only a
string[](array) but also aList<string>orIEnumerable<string>.
This method is highly efficient for implementing processes that “keep a history,” such as recording logs or accumulating data.
