如何逐行读取文件并打印到文本框c#

How to read file line by line and print to a text box c#

我正在开发一个 windows 表单应用程序,我想从我的本地计算机获取一个文本文件并让应用程序读取该文本文件并将文件中的每一行文本显示到应用程序。我想按下窗体上的一个按钮并显示文本文件的第一行,然后再次按下按钮并显示第二行等。我一直在寻找方法来做到这一点并发现 StreamReader 将可能最适合我想要实现的目标。

我目前有以下代码,但它似乎将每一行都打印到一行上。如果有人能看出原因,将不胜感激,我确定它很小。

private void btnOpen_Click(object sender, EventArgs e)
{
    string file_name = "G:\project\testFile.txt";
    string textLine = "";

    if (System.IO.File.Exists(file_name) == true)
    {
        System.IO.StreamReader objReader;
        objReader = new System.IO.StreamReader(file_name);

        do
        {
            textLine = textLine + objReader.ReadLine() + "\r\n";
        } while (objReader.Peek() != -1);

        objReader.Close();
    }
    else
    {
        MessageBox.Show("No such file " + file_name);
    }

    textBox1.Text = textLine;
}

textLine = textLine + objReader.ReadLine() + "\r\n";

替换为以下代码

textLine = textLine + objReader.ReadLine() + Environment.NewLine;

我会按照以下方式进行:

您正在使用 Windows 表单,因此您有一个 Form class 作为您的主要 class。

在这个class中我会定义:

private string[] _fileLines;
private string _pathFile;
private int _index = 0;

在构造函数中我会做

_fileLines = File.ReadAllLines(_pathFile);

在按钮点击事件处理程序中我会做:

textBox1.Text = _fileLines[_index++];

给定

private string[] lines;
private int index =0;

点击事件

// fancy way of intializing the lines array
lines = lines ?? File.ReadAllLines("somePath");

// sanity check 
if(index < lines.Length)
   TextBox.Text = lines[index++]; // index++ increments after use

其他资源

File.ReadAllLines Method

Opens a text file, reads all lines of the file into a string array, and then closes the file.

?? Operator (C# Reference)

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

++ Operator (C# Reference)

The unary increment operator ++ increments its operand by 1. It's supported in two forms: the postfix increment operator, x++, and the prefix increment operator, ++x.

更新

if I was to have the text file update with new lines constantly and I want to read one line after another with the button click, how would i go about that?

你可以只对行使用局部变量,每次只读文件

var lines = File.ReadAllLines("somePath");
if(index < lines.Length)
   TextBox.Text = lines[index++];

您可以这样逐行读取文本文件:

public int buttonClickCounter = 0;
private void button1_Click_1(object sender, EventArgs e)
{   
   List<string> fileContentList = new List<string>();
   string fileInfo = "";
   StreamReader reader = new StreamReader("C://Users//Rehan Shah//Desktop//Text1.txt");
   while ((fileInfo = reader.ReadLine()) != null)
   {
      fileContentList.Add(fileInfo);
   }

   try
   {
      listBox1.Items.Add(fileContentList[buttonClickCounter]);
      buttonClickCounter++;
   }
   catch (Exception ex)
   {
      MessageBox.Show("All Contents is added to the file.");
   }
}