从文本文件中读取一行并返回

Ara*_*hdn 2 c# file-io text

我正在开发一个C#应用程序,我需要从文本文件中读取一行并返回到第一行.

由于文件大小可能太大,我无法将其复制到数组中.

我试过这段代码

StreamReader str1 = new StreamReader(@"c:\file1.txt");
StreamReader str2 = new StreamReader(@"c:\file2.txt");

int a, b;
long pos1, pos2;

while (!str1.EndOfStream && !str2.EndOfStream)
{
    pos1 = str1.BaseStream.Position;
    pos2 = str2.BaseStream.Position;

    a = Int32.Parse(str1.ReadLine());
    b = Int32.Parse(str2.ReadLine());
    if (a <= b)
    {
        Console.WriteLine("File1 ---> " + a.ToString());
        str2.BaseStream.Seek(pos2, SeekOrigin.Begin);
    }
    else
    {
        Console.WriteLine("File2 ---> " + b.ToString());
        str1.BaseStream.Seek(pos1, SeekOrigin.Begin);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我发现程序时,我发现str1.BaseStream.Position并且str2.BaseStream.Position在每个循环中都是相同的,所以什么都不会改变.

有没有更好的方法?

谢谢

cuo*_*gle 8

您可以使用ReadLines大文件,它是延迟执行并且不会将整个文件加载到内存中,因此您可以操作IEnumerable类型中的行:

var lines = File.ReadLines("path");
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧的.NET版本,请参阅以下内容ReadLines:

    public IEnumerable<string> ReadLine(string path)
    {
        using (var streamReader = new StreamReader(path))
        {
            string line;
            while((line = streamReader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)