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.
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();
}
}
}
@elgonzo - The
Sleep
was in the OP. I edited it out, then a second ago I edited from this answer. This answer contained it from the OP's code.No I'm still learning and adding the sleeps allows me to observe everything that's happening. I just put them in there for educational purposes :P
@elgonzo I literally copied OP's example. What Isabelle's purpose of sleeping is, doesn't matter to me. I answered her question. Downvoting shouldn't happen for this reason. I answered the matter.
Already deleted my comment after noticing Scott editing the answer to make it fit the edited question ;-) So, all is good...