簡體   English   中英

將字符串轉換為字符串數組:運行時異常

[英]Converting string to string array: Runtime Exception

我有一個非常簡單的代碼:

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" };

然后我可以在TextBox中讀取Hello World

我是否在從字符串轉換為字符串[]時出錯了?

我想我在這里看到了這個問題:

File.ReadAllLines("@D:\3Dprinter\TestObject1.gcode")

應該讀作為

File.ReadAllLines(@"D:\3Dprinter\TestObject1.gcode")

它目前的方式,可能是找不到文件並返回null; 因為允許字符串為null,所以它會進入循環,然后在嘗試從不存在的數組中獲取值時會停止。

您的文件中可能有一個或多個空行。

您可以通過檢查數組大小是否大於0來輕松解決此問題。

像那樣:

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

IndexOutOfRangeException。 主要是因為嘗試在數組中獲取相應索引的值,該數組實際上小於您要查找的索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM