在 C# 中追加到文本文件
本教程将讨论在 C# 中追加文本文件的方法。
在 C# 中使用 File.AppendAllText()
方法向文本文件追加内容
C# 中的 File.AppendAllText()
方法用于打开现有文件,将所有文本附加到文件末尾,然后关闭文件。如果文件不存在,则 File.AppendAllText()
方法将创建一个新的空文件并将数据写入其中。File.AppendAllText()
方法采用文件路径和要写入的文本作为参数。以下代码示例向我们展示了如何使用 C# 中的 File.AppendAllText()
方法将数据追加到文本文件中。
using System;
using System.IO;
namespace append_to_file
{
class Program
{
static void Main(string[] args)
{
File.AppendAllText(@"C:\File\file.txt", "This is the new text" + Environment.NewLine);
}
}
}
运行代码前的 file.txt
:
this is all the text in this file
运行代码后的 file.txt
:
this is all the text in this file
This is the new text
在上面的代码中,我们用 C# 中的 File.AppendAllText()
方法在路径 C:\File
内的 file.txt
的末尾附加了文本 This is new text
,并在 file.txt
文件的末尾添加了新行。
在 C# 中使用 StreamWriter
类附加到文本文件
我们可以通过 StreamWriter
类实现相同的目标。StreamWriter
类用于将文本写入 C# 中的流或文件。SreamWriter.WriteLine()
方法用 C# 编写了整行。我们可以使用 File.AppendText()
方法初始化 StreamWriter
类的对象,以初始化 StreamWriter
类的实例,该实例会将数据附加到文件中。以下代码示例向我们展示了如何使用 C# 中的 StreamWriter
类将数据追加到文本文件的末尾。
using System;
using System.IO;
namespace append_to_file
{
class Program
{
static void Main(string[] args)
{
using (StreamWriter sw = File.AppendText(@"C:\File\file.txt"))
{
sw.WriteLine("This is the new text");
}
}
}
}
运行代码前的 file.txt
:
this is all the text in this file
运行代码后的 file.txt
:
this is all the text in this file
This is the new text
在上面的代码中,我们使用 sw.WriteLine()
方法在文本 file.txt
的末尾附加了文本 This is new text
和新行。在 C# 中。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。