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上打印出来。这是行不通的。
如果您只想要第一行:
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
语句)。