Home >Backend Development >C++ >How Can I Add a Single Line to a Text File Without Overwriting It?

How Can I Add a Single Line to a Text File Without Overwriting It?

Barbara Streisand
Barbara StreisandOriginal
2025-01-14 20:46:48951browse

How Can I Add a Single Line to a Text File Without Overwriting It?

Append a single line of text to an existing text file

Goal: Append a line of text to an existing text file without overwriting the existing content.

Solution:

For this you can use the File.AppendAllText method. This method accepts two parameters:

  1. The path to the text file to which the text is to be appended.
  2. The text content you wish to add to the file.

Example usage:

<code class="language-csharp">File.AppendAllText(@"c:\path\file.txt", "文本内容" + Environment.NewLine);</code>

Instructions:

  • The first parameter specifies the path to the text file. In this example, we assume the file is located at c:pathfile.txt.
  • The second parameter is the text string to be appended to the file. To ensure that a newline is created after the text, we append it using Environment.NewLine. This is necessary to create new lines in text files.

Use File.AppendAllText to conveniently add a line of text to an existing file without affecting its current content.

The above is the detailed content of How Can I Add a Single Line to a Text File Without Overwriting It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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