2013-10-21 57 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); 
相关问题