我想從一個文本文件加載到我的程序中的數據字段名稱,並將它們存儲到變量,數組中。不明白爲什麼我得到一個IndexOutOfRangeException
字段名稱將用於將來自其他文件的數據分類並打印到有序的新文檔中。
我在將文件中的字段存儲到數組中時遇到了很多麻煩。
數據字段文本文件以列表方式組織,每個字段位於其自己的行上。
我去創建一個while循環,直到StreamReader的Peek()等於-1。
我在while循環中嵌套了一個for循環,它將索引整數變量加1,直到它小於或等於文本文件中的總行數。
它還使用ReadLine()將一行文本文檔存儲到特定索引處的數組中。我認爲在for循環中使用它會遍歷每行並存儲它需要存儲的內容。
我將需要使用字典中的字段,以便我可以使用字段作爲鍵和來自其他文檔的數據作爲字典的值,當我開始顯示該信息時。
我認爲我已經做到這一點的方式將有必要的措施,以避免IndexOutOfRangeException,但我想不是這種情況。
我希望有人願意幫助我。如果有什麼不清楚的地方,我會表示歉意,並會在需要時澄清事情。
如果我試圖解釋的邏輯是可怕的,下面的代碼:
class Program
{
protected static string[] dataFields = new string[] { };
static void Main(string[] args)
{
int iIndex;
using (StreamReader titleStream = new StreamReader(@"..\..\DataFieldsLayout.txt"))
{
while (titleStream.Peek() > -1)
{
for (iIndex = 0; iIndex <= 150; iIndex++)
{
// where the exception occurs
dataFields[iIndex] = titleStream.ReadLine();
}
}
}
// test
Console.WriteLine(dataFields[0]);
Console.WriteLine(dataFields[1]);
Console.WriteLine(dataFields[2]);
Console.WriteLine(dataFields[3]);
Console.WriteLine(dataFields[4]);
}
}
可能重複[什麼是IndexOutOfRangeException,我該如何解決它?](http://stackoverflow.com/questions/20940979/what-is-indexoutofrangeexception-and-how-do-i-fix-it) –
你已經聲明瞭一個包含零元素的字符串數組,在這個數組上不可能使用任何類型的索引。 – Steve
另一點。你確定你的文件總是包含151行或151的倍數嗎? – Steve