【问题标题】:Streamreader and "Index was outside the bounds of the array" errorStreamreader 和“索引超出数组范围”错误
【发布时间】:2017-02-02 07:15:01
【问题描述】:

我没有写任何数组长度,但是当我尝试读取 .csv 文件时,我得到 “索引超出数组范围” 错误。 .csv 文件大约有 1 000 000 行。有没有人修复这个代码?

.csv 文件行如下所示。

0000000,26.0000000000000,38.0000000000000,30.01.2017,0,0,0,,,0,0,,0,,0,0,0,0

string[] read;
char[] seperators = { ',' };


        try
        {
            Image img = Image.FromFile(txtFilePath.Text); 
            Graphics g = Graphics.FromImage(img);
            pictureBox1.Image = img;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

            StreamReader sr = new StreamReader(txtFile2Path.Text);

            string data;

            while ((data=sr.ReadLine()) !=null)
            {
                read = data.Split(seperators, StringSplitOptions.None);

                float x = float.Parse(read[1]);
                float y = float.Parse(read[2]);
                string z = read[10];
            }
        }


        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }      

【问题讨论】:

  • 在调试模式下看这行float x = float.Parse(read[1]); float y = float.Parse(read[2]);string z = read[10];
  • 如果 read.Length >= 11,您可能需要一个 if 条件
  • 在调试模式下这些行没有错误。在调试模式下,Visual Studio 中的一切看起来都是正确的。
  • 这是运行时错误,在这行设置断点并检查read.Length >= 11是否有@Ben所说的
  • 如果条件 read.Length >= 11 适用于代码。非常感谢您的帮助。

标签: c# arrays csv streamreader


【解决方案1】:

只是为了澄清任何在这里结束的人的答案..

        while ((data=sr.ReadLine()) !=null)
        {
            read = data.Split(seperators, StringSplitOptions.None);
            if (read.Length >= 11)
            {
                float x = float.Parse(read[1]);
                float y = float.Parse(read[2]);
                string z = read[10];
            }
        }

访问可能不是所需长度的数组时,请先检查它。

Index was outside the bounds of the array 异常只会在一行代码尝试访问数组中不存在的项 (N-1) 时引发 - 由于数组中的项少于 (N) 个

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2017-05-06
    相关资源
    最近更新 更多