如何以C#格式很好地访问我的.txt,我需要.txt文件的第一行才能在TextBox上打印出来

问题描述 投票:-1回答:1
private void Button1_Click(object sender, EventArgs e)
{
    int counter = 0;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader("Sav1.txt");
    while ((line = file.ReadLine()) != null)
    {
        richTextBox1.Items.Add(line);
        counter++;
    }
}

如何以C#格式很好地访问.txt,我需要.txt文件的第一行才能在TextBox上打印出来。这是行不通的。

c# winforms textbox
1个回答
0
投票

如果您只想要第一行:

int counter = 0;
string line;
using (System.IO.StreamReader file = new System.IO.StreamReader("Sav1.txt"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (counter == 0)
        {
            richTextBox1.Items.Add(line);
        }
        counter++;
    }
}

如果您不需要该文件,则可以执行以下操作:

    string line;
    using (System.IO.StreamReader file = new System.IO.StreamReader("Sav1.txt"))
    {
        if ((line = file.ReadLine()) != null)
        {
            richTextBox1.Items.Add(line);
        }
    }
}

请注意,无论哪种方式,您都应始终将Dispose实例的StreamReader(最简单的方法是using语句)。

© www.soinside.com 2019 - 2024. All rights reserved.