附加文本文件后,我希望控制台写入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添加此行”行。但是我所得到的只是旧文本。
您应该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();
}
}
}
@elgonzo-
Sleep
在OP中。我将其编辑掉了,然后又一秒钟前从这个答案中进行了编辑。这个答案包含在OP的代码中。不,我仍在学习,添加睡眠使我可以观察正在发生的一切。我只是出于教育目的将它们放在其中:P
@elgonzo我从字面上复制了OP的示例。伊莎贝尔睡觉的目的是什么,对我来说无关紧要。我回答了她的问题。出于这个原因,不应该进行投票表决。我回答了这个问题。
在注意到Scott编辑答案以使其适合所编辑的问题之后,已经删除了我的评论;-)所以,一切都很好...