2013-10-21 56 views
1

我是C#和編程的新手。我正在嘗試讀取txt文件的內容並將它們加載到arraylist。我無法弄清楚在我的while循環中使用什麼條件。如何讀取txt文件並將內容加載到數組列表中?

void LoadArrayList() 
{ 
    TextReader tr; 
    tr = File.OpenText("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt"); 

    string Actor; 
    while (ActorArrayList != null) 
    { 
     Actor = tr.ReadLine(); 
     if (Actor == null) 
     { 
      break; 
     } 
     ActorArrayList.Add(Actor); 
    } 
} 
+2

搜索'File.ReadAllLines'做到這一點,應該讓你接近你所需要的。 – carlosfigueira

+1

不要在第一個地方使用'ArrayList'。改爲使用通用的'List '。 – MarcinJuraszek

+0

'variable'名字應該以小寫字母開頭! – sarwar026

回答

1
void LoadArrayList() 
{ 
    TextReader tr; 
    tr = File.OpenText("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt"); 

    string Actor; 
    Actor = tr.ReadLine(); 
    while (Actor != null) 
    { 
     ActorArrayList.Add(Actor); 
     Actor = tr.ReadLine(); 
    } 

} 
+0

與上面的代碼一樣,發生了同樣的事情。它經歷了5次循環。 – Maattt

+0

這是一件好事還是壞事?不知道你的文件中有什麼,我無法說清楚。遍歷調試器中的代碼,並查看循環的每次迭代的Actor的值。這會讓你對發生的事情有所瞭解。 – dav1dsm1th

0

這是應該的

void LoadArrayList() 
{ 
    string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Maattt\Documents\Visual Studio 2010\Projects\actor\actors.txt"); 

    // Display the file contents by using a foreach loop. 
    foreach (string Actor in lines) 
    { 
     ActorArrayList.Add(Actor); 
    } 
} 
0

就重新安排這樣的:

Actor = tr.ReadLine(); 
    while (Actor != null) 
    { 
     ActorArrayList.Add(Actor); 
     Actor = tr.ReadLine(); 
    } 
0

如果你看一下the documentation for the TextReader.ReadLine method,你會看到,它要麼返回如果沒有更多的行,則可以使用stringnull。所以,你可以做的是循環並檢查null與ReadLine方法的結果。

while(tr.ReadLine() != null) 
{ 
    // We know there are more items to read 
} 

雖然如上所述,但您並未捕捉到ReadLine的結果。所以,你需要聲明一個字符串捕獲結果和while循環中使用:

string line; 
while((line = tr.ReadLine()) != null) 
{ 
    ActorArrayList.Add(line); 
} 

另外,我建議使用一個通用的列表,如List<T>代替非通用ArrayList。使用諸如List<T>之類的東西可以爲您提供更多的類型安全性,並減少無效分配或強制轉換的可能性。

1

您可以只兩行代碼

string[] Actor = File.ReadAllLines("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt"); 
ArrayList list = new ArrayList(Actor); 
相關問題