C#System.IndexOutOfRangeException:'索引超出了数组的范围。'将文本添加到文本框时

时间:2017-08-23 18:57:42

标签: c#

我试图制作一个程序,在文本文件的每一行的开头添加一些内容,并将其写入文本框,然后我在行textBox2.Lines[c] = "STRING " + lines[c] + "\nENTER\n";上收到错误。< / p>

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)
    {

    }
}
}

1 个答案:

答案 0 :(得分:1)

for循环的最后一次迭代中

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

c等于lines.Length。尝试访问lines[lines.Length]将始终在检测到缓冲区溢出的语言中导致异常(即不是C或C ++)。

尝试替换

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