Warm tip: This article is reproduced from stackoverflow.com, please click
.net c#

How to write text in console after appending?

发布于 2020-03-27 10:17:17

After appending a text file I want the console to write the new complete text of the txt file. However, the line I've just added is not written in the console. What am I doing wrong?

You can see my code below.

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();
        }
    }
}

In the end, I expect to read the text already present in the file and the line "This line is added by Visual Studio". But all I'm getting is the old text.

Questioner
Isabelle
Viewed
149
18.6k 2019-07-03 21:37

You should set the lines variable again after appending your text, like you originally did.

lines = File.ReadAllText(path);

Which results in the following for you:

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();
        }
    }
}