C# - Appending text files

前端 未结 4 2096
遇见更好的自我
遇见更好的自我 2020-12-31 13:24

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

相关标签:
4条回答
  • 2020-12-31 13:28

    Try

    StreamWriter writer = File.AppendText("C:\\test.txt");
    writer.WriteLine(mystring);
    
    0 讨论(0)
  • 2020-12-31 13:29

    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);
    }
    
    0 讨论(0)
  • 2020-12-31 13:42
    using(StreamWriter file = File.AppendText(@"c:\test2.txt"))
    {
        file.WriteLine(myString);
    }
    
    0 讨论(0)
  • 2020-12-31 13:48

    Use File.AppendAllText

    File.AppendAllText("c:\\test2.txt", myString)
    

    Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.

    0 讨论(0)
提交回复
热议问题