append to a file in csharp

To append data to an existing file in C#, you can use the StreamWriter class. StreamWriter appends text to a file by default if the file exists, but if the file does not exist, it will create a new file.

Here's an example code snippet that demonstrates how to use StreamWriter to append text to a file:

main.cs
using System.IO;

class Program {
    static void Main(string[] args) {
        string filePath = @"C:\example\file.txt";
        string textToAppend = "This is some text to append.";

        using (StreamWriter writer = new StreamWriter(filePath, true)) {
            writer.WriteLine(textToAppend);
        }
    }
}
320 chars
13 lines

In this example, we first specify the file path and the text that we want to append to the file. We then create a new StreamWriter using the file path and set the second parameter to true so that it will append text to an existing file. Finally, we use the WriteLine method to append the text to the file.

Note that we use a using statement to ensure that the StreamWriter object is disposed of properly and the file is closed after the data has been written.

gistlibby LogSnag