C# 如何从 .t​​xt 文件中的列表中读取并将它们放入列表中?

标签 c# visual-studio

<分区>

当我在列表框中显示它们时,我只是写了“(Collection)”而不是实际文本。

最佳答案

您应该逐行阅读文本文件并将它们添加到列表中。在它之后你可以通过你的列表设置你的ListBox DataSource。尝试:

   const string f = "TextFile1.txt";

    // 1
    // Declare new List.
    List<string> lines = new List<string>();

    // 2
    // Use using StreamReader for disposing.
    using (StreamReader r = new StreamReader(f))
    {
        // 3
        // Use while != null pattern for loop
        string line;
        while ((line = r.ReadLine()) != null)
        {
        // 4
        // Insert logic here.
        // ...
        // "line" is a line in the file. Add it to our List.
        lines.Add(line);
        }
    }

    // 5
    // Print out all the lines.
    foreach (string s in lines)
    {
        Console.WriteLine(s);
    }

Read More

关于C# 如何从 .t​​xt 文件中的列表中读取并将它们放入列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31509483/

相关文章:

visual-studio - Visual Studio 中的 yacc 和 Bison

c# - 如何只复制一个DataTable中的列到另一个DataTable?

c# - 如何在 C# 中将流保存到文件?

visual-studio - 在预编译头文件中包含 resource.h 是个好主意吗?

c# - Selenium C# 无法使用 FindElements 获取列表

c# - 编辑数据网格行

c# - 如何使用最小条件和附加条件优化 LINQ

c# - 将对象从大型 JSON 文件转换为 .NET 中对象的最快方法

c# - 在 Entity Framework 中使用存储过程的乐观并发

c++ - 使用 SSE2 和 AVX2 编译库