Home > Backend Development > C++ > How Do I Append Lines to a File Using C# StreamWriter?

How Do I Append Lines to a File Using C# StreamWriter?

Susan Sarandon
Release: 2025-01-19 10:01:12
Original
717 people have browsed it

How Do I Append Lines to a File Using C# StreamWriter?

Append lines to file using StreamWriter

When working with files in C#, a common task is to append lines to an existing file. However, by default, StreamWriter overwrites the contents of the file.

To enable append functionality, use the StreamWriter constructor with the bool append parameter. Set the parameter to true to append to the file.

In earlier versions of C#, the syntax was as follows:

<code class="language-c#">new StreamWriter("c:\file.txt", true);</code>
Copy after login

In C# 4 and above, a more readable syntax is available:

<code class="language-c#">new StreamWriter("c:\file.txt", append: true);</code>
Copy after login

This syntax explicitly specifies that the file should be opened in append mode, ensuring that subsequent write operations append to the existing content.

Example:

<code class="language-c#">using System.IO;

public class AppendToFile
{
    public static void Main()
    {
        using (var file = new StreamWriter("c:\file.txt", append: true))
        {
            file.WriteLine("Line 1");
            file.WriteLine("Line 2");
        }
    }
}</code>
Copy after login

By using the append parameter you can control the behavior of the StreamWriter, allowing you to append lines to an existing file without overwriting the file contents. Please note that the using statement is used in the example, which is a safer way to ensure that the file is automatically closed after use, even if an exception occurs.

The above is the detailed content of How Do I Append Lines to a File Using C# StreamWriter?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template