2

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

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;
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • Possible duplicate of [How to add a line to a multiline TextBox?](https://stackoverflow.com/questions/8536958/how-to-add-a-line-to-a-multiline-textbox) – Dani Jan 04 '19 at 07:31
  • If you want to read one line for each btn click you couldn't use while loop to read whole file. You must only perform .ReadLine() per one btn click. Secondly, you must use multiline text box. – ElConrado Jan 04 '19 at 07:34
  • Stream's are not being opened during whole process. You should get all lines into a field then loop through them. If you have very big files you can try memorize Stream scroll through button pressed events. – darcane Jan 04 '19 at 07:38
  • @ElConrado you could just read the whole file, store each line in a variable (perhaps List) and then just use an indexer and add a new line that way? – Dennis Vanhout Jan 04 '19 at 08:14

4 Answers4

6

I would do it in a following way:

you are working with Windows Forms, so you have a Form class as your main class.

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++];
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
4

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

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.

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++];
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • Perfect works great thanks, 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? Would this solution not work as it reads all lines at the start of the program? would I be able to loop to check for line updates? – Richard Motion Jan 04 '19 at 08:08
1

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.");
   }
}
Rehan Shah
  • 1,505
  • 12
  • 28
-1

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

replace with below code

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

Rehan Shah
  • 1,505
  • 12
  • 28
  • 2
    `Environment.NewLine` is just a [static property](https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline?view=netframework-4.7.2) containing `"\r\n"` or `"\n"` depending if the platform is Unix or not. I agree that is better to have it than `"\r\n"`, but it's not gonna solve his problem. – ikerbera Jan 04 '19 at 07:35