0

I'm trying to make a program that adds something to the beginning of each line of a text file, and writes it to a text box, and I get that error on the line textBox2.Lines[c] = "STRING " + lines[c] + "\nENTER\n";.

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TextDucky
{
public partial class Form1 : Form
{
    string path;
    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Open.InitialDirectory = "c:\\";
        Open.Filter = "Text Files (*.txt)|*.txt";
        Open.FilterIndex = 2;
        Open.RestoreDirectory = true;
        Open.ShowDialog();
        path = Open.FileName;
        string[] lines = File.ReadAllLines(path);
        Console.Write(lines);
        for (int c = 0; c <= lines.Length; c++)
        {
            textBox2.Lines[c] = "STRING " + lines[c] + "\nENTER\n";
        }
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {

    }

    private void Open_HelpRequest(object sender, EventArgs e)
    {

    }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }
}
}
BomberF35
  • 13
  • 4

1 Answers1

1

In the last iteration of your for loop

for (int c = 0; c <= lines.Length; c++)

c is equal to lines.Length. Trying to access lines[lines.Length] will always cause an exception in a language that detects a buffer overflow (i.e. not C or C++).

Try replacing with

for (int c = 0; c < lines.Length; c++)
yinnonsanders
  • 1,831
  • 11
  • 28