简体   繁体   English

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

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

I am working on a windows forms application and am wanting to take a text file from my local machine and have the application read the text file and display each line of text from the file into a textbox on the application. 我正在Windows窗体应用程序上工作,希望从本地计算机上获取文本文件,并让该应用程序读取文本文件,并将文件中的每一行文本显示到应用程序的文本框中。 I am wanting to press a button on the form and have the first line of the text file display, then press the button again and have the second line display etc.. I have been looking for ways to do this and have found that StreamReader will probably be best for what I am wanting to achieve. 我想按一下表单上的按钮,并显示文本文件的第一行,然后再次按该按钮,并显示第二行,等等。我一直在寻找实现此目的的方法,并且发现StreamReader可以可能是我想要实现的最佳选择。

I currently have the below code but it seems to print every line onto one line. 我目前有以下代码,但似乎将每一行打印到一行上。 If anybody can see why, it would be greatly appreciated, im sure that its something small. 如果有人能看到原因,那将不胜感激,我肯定它很小。

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;
}

I would do it in a following way: 我会通过以下方式做到这一点:

you are working with Windows Forms, so you have a Form class as your main class. 您正在使用Windows Forms,因此您有一个Form类作为主类。

In this class I would define: 在本课程中,我将定义:

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

and in constructor I would do 在构造函数中,我会做

_fileLines = File.ReadAllLines(_pathFile);

and in button click event handler I would do: 在按钮单击事件处理程序中,我将执行以下操作:

textBox1.Text = _fileLines[_index++];

Given 给定

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

Click Event 点击事件

// 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

Additional Resources 其他资源

File.ReadAllLines Method File.ReadAllLines方法

Opens a text file, reads all lines of the file into a string array, and then closes the file. 打开一个文本文件,将文件的所有行读入字符串数组,然后关闭文件。

?? ?? Operator (C# Reference) 运算符(C#参考)

The ?? ?? operator is called the null-coalescing operator. 运算符称为空值运算符。 It returns the left-hand operand if the operand is not null; 如果操作数不为null,则返回左侧的操作数;否则,返回0。 otherwise it returns the right hand operand. 否则返回右手操作数。

++ Operator (C# Reference) ++运算符(C#参考)

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. 一元递增运算符++将其操作数递增1。它受两种格式支持:后缀递增运算符x ++和前缀递增运算符++ x。

Update 更新资料

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? 如果我要不断用新行更新文本文件,并且我想单击按钮逐行阅读,那我该怎么办?

You can just use a local variable for lines, and just read the file every time 您可以仅将局部变量用于行,并且每次都仅读取文件

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

You can Read a text file line by line in this way: 您可以通过以下方式逐行读取文本文件:

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.");
   }
}

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

用下面的代码替换

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM