如何读取 txt 文件并将内容加载到数组列表中

本文关键字:加载 数组 列表 何读取 读取 文件 txt | 更新日期: 2023-09-27 18:36:06

我是C#和一般编程的新手。我正在尝试读取 txt 文件的内容并将它们加载到arraylist.我不知道在我的while循环中使用什么条件。

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

如何读取 txt 文件并将内容加载到数组列表中

 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();
    }
}

您只需 2 行代码即可完成

string[] Actor = File.ReadAllLines("C:''Users''Maattt''Documents''Visual Studio 2010''Projects''actor''actors.txt");
ArrayList list = new ArrayList(Actor);
应该是

这样的

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

只需像这样重新排列它:

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

如果您查看 TextReader.ReadLine 方法的文档,您会发现它返回 string ,如果没有更多行,则返回null。因此,您可以做的是循环并根据 ReadLine 方法的结果检查 null。

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> 的内容可以为您提供更多的类型安全性,并减少无效赋值或强制转换的可能性。