温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How to write text in console after appending?
.net c#

c# - 附加后如何在控制台中编写文本?

发布于 2020-03-27 10:29:44

附加文本文件后,我希望控制台写入txt文件的新完整文本。但是,我刚刚添加的行未写在控制台中。我究竟做错了什么?

您可以在下面看到我的代码。

using System;
using System.IO;

namespace FileExercise
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Text.txt";    

            //Read all lines    
            string lines = File.ReadAllText(path);

            Console.WriteLine(lines);   

            //Add line to original document
            File.AppendAllLines(@path, new string[] { "" + "This line is added 
            by Visual Studio" });   

            //Read new lines
            Console.WriteLine(lines);

            Console.ReadKey();
        }
    }
}

最后,我希望读取文件中已经存在的文本和“ Visual Studio添加此行”行。但是我所得到的只是旧文本。

查看更多

查看更多

提问者
Isabelle
被浏览
228
18.6k 2019-07-03 21:37

您应该lines像最初那样在追加文本后再次设置变量。

lines = File.ReadAllText(path);

为您带来以下结果:

using System;
using System.IO;

namespace FileExercise
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Text.txt";    

            //Read all lines
            string lines = File.ReadAllText(path);

            Console.WriteLine(lines);

            //Add line to original document
            File.AppendAllLines(@path, new string[] { "" + "This line is added 
            by Visual Studio" });    

            lines = File.ReadAllText(path);

            //Read new lines
            Console.WriteLine(lines);

            Console.ReadKey();
        }
    }
}