gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:43:16 25 4
gpt4 key购买 nike

我正在开发一个 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);
}
}

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

有没有更好的办法?

谢谢

最佳答案

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

var lines = File.ReadLines("path");

如果您使用的是旧的 .NET 版本,下面是如何自己构建 ReadLines:

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

关于c# - 从文本文件中读取一行并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15656089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com