C# 一个一次读5行而不是一行的流阅读器是可能的吗?
我使用C# 一个一次读5行而不是一行的流阅读器是可能的吗?,c#,C#,我使用StreamReader,但它一次只能读取一行 我的问题是:是否有可能改变这种行为,使我可以阅读多个?例如:一次5行 using System; using System.IO; using System.Text.RegularExpressions; using System.Linq; using System.Collections.Generic; class example { public static void Main() { var
StreamReader
,但它一次只能读取一行
我的问题是:是否有可能改变这种行为,使我可以阅读多个?例如:一次5行
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
class example
{
public static void Main()
{
var path = "pruebastream.txt";
var path2 = "pruebastream2.txt";
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
using (StreamWriter outputFile = new StreamWriter(path2))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var text = ProcessLine(line);
outputFile.WriteLine(text);
}
}
}
static string ProcessLine(string text)
{
}
}
这可能会被否决一点,但更简单的方法是只使用5
。ReadLine
:
using (var sr = File.OpenText("1.txt"))
using (var sw = File.CreateText("2.txt"))
{
while (!sr.EndOfStream)
{
var s = sr.ReadLine() + "\r\n" + sr.ReadLine() + "\r\n" +
sr.ReadLine() + "\r\n" + sr.ReadLine() + "\r\n" + sr.ReadLine();
}
}
否则,如果您不想在最后几行之后使用额外的换行符,请使用计数器变量。如果您仍然需要同时处理一行,那么一起读取5行将没有什么好处。您能解释一下为什么一次需要读取5行吗?是的,通常我使用一个regex命令,但是这个命令可以在多行(它是一个comand,用于表的sum元素)的情况下工作。您可以为StreamReader编写一个扩展,在数组中加载5行并返回它(但如果文件中的行数不完全是5的倍数,则仍需要检查读取的行数是否少于5行)如果要每隔5行调用该方法,为什么不使用计数器?然后
if(i%5==0)//调用该方法。
另一种方法是读取和存储所有行,每次处理5行。如果文件太大,后一种方法将是内存问题。@jhonny625 50MB什么都不是。使用file.ReadAllLines()一次性读取所有行,这将为您提供一个行数组。如果您需要将其拆分为多个批,可以使用Linq接管数组。是的,为什么不应该使用它?由于您没有为每个ReadLine检查sr.EndOfStream,代码将在99%的时间内崩溃。@SledgeHammer这是原因之一。。假设不进行测试(我也经常这样做)。.ReadLine()
无论调用多少次,都只返回null。我在发布之前测试了代码。SledgeHammer我对此有点困惑,问题是如果我将命令分成几行,那么命令不能使用多行