C# - 附加文本文件

Ben*_*Ben 10 .net c# windows

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

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();
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*Aza 15

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

var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);
Run Code Online (Sandbox Code Playgroud)

如果文件很大,您可以逐行读写:

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


Bro*_*ass 8

using(StreamWriter file = File.AppendText(@"c:\test2.txt"))
{
    file.WriteLine(myString);
}
Run Code Online (Sandbox Code Playgroud)


Yur*_*ich 5

使用File.AppendAllText

File.AppendAllText("c:\\test2.txt", myString)
Run Code Online (Sandbox Code Playgroud)

另外,要阅读它,您可以使用File.ReadAllText来读取它.否则using,在完成文件后,使用语句来处理流.