C# - 我如何读取txt文件中的最后一行

时间:2018-04-24 15:58:46

标签: c#

我如何读取txt文件中的最后一行并将其写入" RichTextBox" ?

现在我有了这个:

StreamWriter sw2 = new StreamWriter(Application.StartupPath + "\\Notes\\" + FileTxtBox.Text + "_" + "note" + ".txt");
sw2.WriteLine(NoteTxtBox.Text);
w2.Close();

StreamReader sr = new StreamReader(Application.StartupPath + "\\Notes\\" + FileTxtBox.Text + "_" + "note" + ".txt");
ShowBOX.Text = sr.ReadToEnd();
sr.Close();

2 个答案:

答案 0 :(得分:6)

TextBox.Text = File.ReadLines("filename.txt").Last();

File.ReadLines(...)会返回IEnumerable<string>.Last()是一个LINQ方法,它从IEnumerable获取最后一项(所以在这种情况下,是文件的最后一行)。

答案 1 :(得分:2)

对于实时最后一行,请在流程中启动PowerShell并使用Tail

void Main()
{
    var fileName = @"C:\BrianTemp\Log.txt";
    var arg = $"Get-Content {fileName} -Wait -Tail 30";
    launchPowershell(arg);
    Console.ReadLine();
}

static void launchPowershell(string arg)
{
    Process proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "powershell",
            Arguments = arg,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        }
    };

    proc.Start();
    while (!proc.StandardOutput.EndOfStream)
    {
        string line = proc.StandardOutput.ReadLine();
        Console.WriteLine(line);//TODO: do something with line
    }
}