gpt4 book ai didi

c# - 获取文本文件中行数的估计值

转载 作者:行者123 更新时间:2023-11-30 17:39:24 28 4
gpt4 key购买 nike

我想估计 csv/文本文件中的行数,以便我可以将该数字用于进度条。该文件可能非常大,因此获取准确的行数将花费太长时间。

我的想法如下(读取文件的一部分并计算行数并使用文件大小来估计总行数):

    public static int GetLineCountEstimate(string file)
{
double count = 0;
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
long byteCount = fs.Length;
int maxByteCount = 524288;
if (byteCount > maxByteCount)
{
var buf = new byte[maxByteCount];
fs.Read(buf, 0, maxByteCount);
string s = System.Text.Encoding.UTF8.GetString(buf, 0, buf.Length);
count = s.Split('\n').Length * byteCount / maxByteCount;
}
else
{
var buf = new byte[byteCount];
fs.Read(buf, 0, (int)byteCount);
string s = System.Text.Encoding.UTF8.GetString(buf, 0, buf.Length);
count = s.Split('\n').Length;
}
}
return Convert.ToInt32(count);
}

这似乎工作正常,但我有一些顾虑:

1) 我希望我的参数只是 Stream(而不是文件名),因为我也可能从剪贴板 (MemoryStream) 读取数据。但是,Stream 似乎无法一次将 n 个字节读入缓冲区或以字节为单位获取 Stream 的总长度,就像 FileStream 一样。 Stream 是 MemoryStream 和 FileStream 的父类。

2) 我不想采用 UTF8 之类的编码

3) 我不想假定行尾字符(它应该适用于 CR、CRLF 和 LF)

我将不胜感激任何帮助,使这个功能更强大。

最佳答案

这是我想出的更强大的估计行数解决方案。

public static int EstimateLineCount(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
return EstimateLineCount(fs);
}
}

public static int EstimateLineCount(Stream s)
{
//if file is larger than 10MB estimate the line count, otherwise get the exact line count
const int maxBytes = 10485760; //10MB = 1024*1024*10 bytes

s.Position = 0;
using (var sr = new StreamReader(s, Encoding.UTF8))
{
int lineCount = 0;
if (s.Length > maxBytes)
{
while (s.Position < maxBytes && sr.ReadLine() != null)
lineCount++;

return Convert.ToInt32((double)lineCount * s.Length / s.Position);
}

while (sr.ReadLine() != null)
lineCount++;
return lineCount;
}
}

关于c# - 获取文本文件中行数的估计值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35569701/

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