C#如何将File.ReadLines转换为字符串数组?

33

我的问题是如何将从文本文件中读取行的过程转换为存储为数组,而不仅仅是读取。

我的代码错误在于 string[] lines = File.ReadLines("c:\\file.txt");,出现了无法隐式转换的错误......

请问有人可以建议一下代码,以数组格式保存结果吗?我已经放置了ReadAllLines代码,它也能够将结果保存为数组。谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Testing
{
class Analysis
{
    static void Main()
    {
        string[] lines = File.ReadLines("c:\\file.txt");

        foreach (string r in lines)
        {
            Console.WriteLine("-- {0}", r);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
}

ReadAllLines 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Testing
{
class ReadFromFile
{
    static void Main()
    {
        string[] lines = System.IO.File.ReadAllLines
        (@"C:\Users\Public\TestFolder\WriteLines2.txt");

        System.Console.WriteLine("Contents of writeLines2.txt =:");
        foreach (string line in lines)
        {
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
}

5
看起来 ReadAllLines 已经能满足你的需求了,那么为什么你还要尝试使用 ReadLines 呢? - Gabe
请查看下面的评论。谢谢。 - JavaNoob
4个回答

55

File.ReadLines() 返回类型为 System.Collections.Generic.IEnumerable<String> 的对象。
File.ReadAllLines() 返回字符串数组。

如果您想使用字符串数组,您需要调用正确的函数。

你可以使用Jim的解决方案,只需使用ReadAllLines()或更改返回类型。

这也可以工作:

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");

你可以使用任何实现了 IEnumerable 接口的通用集合,例如 IList<String>


ReturnLines 不是一个定义,这就是系统显示的内容。 - JavaNoob
啊,我现在看到我的笔误了。我已经更新了答案,应该是ReadLines。关键是如果您需要一个数组,请使用ReadAllLines()。如果您可以使用集合,对于大文件,ReadLines() 的效果更好,因为只有在需要时才会获取单独的行。 - Gerald Davis
1
是的,这就是允许在ReadLines中使用更大文件的想法。所以上述代码与ReadAllLines不相似对吧? - JavaNoob
正确。实际读取发生在需要特定行时。具体的机制是不透明的,我注意到在一些小文件中,ReadLines 实际上会一次读取所有行。很可能在这个实现中有一些优化,其中不是一次读取单行,而是将一些“块”行读入集合中。 - Gerald Davis

27
string[] lines = File.ReadLines("c:\\file.txt").ToArray();

虽然人们不明白为什么你要那样做,因为 ReadAllLines 工作得很好。

或者也许你只是想用 File.ReadLines 的返回值进行枚举:

var lines = File.ReadLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}

4
但是调用ToArray将抵消调用ReadLines的任何好处。请像我展示的那样使用枚举器。 - Jim Mischel
我不知道枚举器是如何实现的。事实是两者都会将整个文件读入内存。两者之间的区别在于ReadAllLines将整个文件读入内存,然后返回。ReadLines几乎立即返回,允许您在其继续在后台加载文件的同时开始枚举。但我怀疑最终结果非常接近相同的内存量。如果要在读取大型文本文件时防止内存问题,请使用StreamReader并逐行读取。 - Jim Mischel
4
我很肯定ReadLines会使用StreamReader或类似的方式逐行读取文件,这正是其存在的意义。 - LukeH
1
@LukeH:你说得对。我改口了。返回的 IEnumerable<string> 是一次性对象。例如,如果你枚举所有行,然后调用 Count(),你会得到一个 ObjectDisposedException。我理解为什么会这样,但是如果有人将该 IEnumerator 传递给期望多次查询它的方法,我可以看到这可能会引起一些混乱。 - Jim Mischel
1
@JavaNoob:我之前对ReadLines的实现方式有误。它并不会将整个文件读入内存。你可以使用ReadLines来避免你提到的缓冲区溢出问题。 - Jim Mischel
显示剩余4条评论

2

string[] lines = File.ReadLines("c:\\file.txt");改为IEnumerable<string> lines = File.ReadLines("c:\\file.txt");。您的其他代码应该可以正常工作。


-2
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace FileReader
{
    class Program
    {
        static void Main(string[] args)
        {
            var lines = File.ReadAllLines("D:/Text.txt").ToList();
            if(lines != null && lines.Count  > 0)
            {
                foreach(var line in lines)
                {
                    Console.WriteLine(line);
                }
            }
            Console.ReadKey();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接