Home >Backend Development >C++ >How Do I Append a Single Line to a Text File in C#?

How Do I Append a Single Line to a Text File in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-14 20:51:45879browse

How Do I Append a Single Line to a Text File in C#?

Append single line to text file

This section explains how to append a line of text to an existing text file:

Question:

How do I open a text file, append a line of text to it, and then close the file?

Answer:

This function can be achieved using the File.AppendAllText method:

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

namespace 文件操作
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"c:\path\file.txt";

            // 向文件追加一行文本。
            File.AppendAllText(filePath, "文本内容" + Environment.NewLine);
        }
    }
}</code>

In this example, the File.AppendAllText method takes as parameters the file path and the text content to be appended. Environment.NewLineConstant is used to ensure that text content is appended to the file on a new line.

The above is the detailed content of How Do I Append a Single Line to a Text File in C#?. 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