C#-附加文本文件 [英] C# - Appending text files

查看:91
本文介绍了C#-附加文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有读取文件的代码,然后将其转换为字符串,然后将该字符串写入新文件,尽管有人可以演示如何将此字符串附加到目标文件(而不是覆盖它)

I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)

private static void Ignore()
{
    System.IO.StreamReader myFile =
       new System.IO.StreamReader("c:\\test.txt");
    string myString = myFile.ReadToEnd();

    myFile.Close();
    Console.WriteLine(myString);

    // Write the string to a file.
    System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
    file.WriteLine(myString);

    file.Close();
}


推荐答案

如果文件很小,您可以在两条代码行中进行读写。

If the file is small, you can read and write in two code lines.

var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);

如果文件很大,则可以逐行读取和写入:

If the file is huge, you can read and write line-by-line:

using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
    var line = source.ReadLine();
    destination.WriteLine(line);
}

这篇关于C#-附加文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆