我有一个非常简单的代码:转换字符串字符串数组:运行时异常
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:\3Dprinter\TestObject1.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。
我做从有毛病转换字符串到的String []?
你究竟在用'Select'调用来做什么?如果文件中的某一行没有任何字符,则会发生异常。检查'CurrentLine_Array.Length'来查看数组中是否有任何内容。 – cubrr
好的,这是我的错...... 我**。gcode **文件中的一行根本不包含任何字符。 我只是把整个循环放到try {}和catch {}函数中,并且它现在可以工作:) –
您不需要...在这里捕获异常!只要检查数组的长度是否大于0! – cubrr