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>
In C# 4 and above, a more readable syntax is available:
<code class="language-c#">new StreamWriter("c:\file.txt", append: true);</code>
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>
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!