将字符串转换为字符串数组:运行时异常



我有一个非常简单的代码:

using System;
using System.Linq;
using System.Windows;
using System.IO;
namespace _3DPrinter_Test1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {    
            InitializeComponent();
            foreach (string CurrentLine_Raw in File.ReadAllLines( 
                "@D:3DprinterTestObject1.gcode"))
            {
                string[] CurrentLine_Array = 
                    CurrentLine_Raw.Select(c => c.ToString()).ToArray();
                TextBox_Test.Text = CurrentLine_Array[0];
            }
        }
    }
}

该行

TextBox_Test.Text = CurrentLine_Array[0];

给了我一个IndexOutOfRangeException

在我看来,这是因为这行:

string[] CurrentLine_Array = CurrentLine_Raw.Select(c => c.ToString()).ToArray();

但是当我用这一行替换上面的内容时:

string[] CurrentLine_Array = { "Hello World" };

然后我可以在我的文本框中阅读 Hello World

我在从字符串到字符串[]的转换中做错了吗?

我想我已经在这里看到了问题:

File.ReadAllLines("@D:3DprinterTestObject1.gcode")

可能应该读作

File.ReadAllLines(@"D:3DprinterTestObject1.gcode")

目前的方式是,它可能找不到文件并返回 null;因为字符串被允许为 null,所以它进入循环一次,然后在它尝试从不存在的数组中获取值时失败。

文件中可能有

一个或多个空行。

您可以通过检查数组大小是否大于 0 来轻松解决此问题。

诸如此类:

 if (CurrentLine_Array.Length > 0)
        {
            // DO SOMETHING
        }

IndexOutOfRangeException. 主要是由于试图在数组中获取相应 Index 的值,该值实际上小于您要查找的 Index。

最新更新