【发布时间】:2016-02-23 05:40:14
【问题描述】:
我想估计 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)
我将不胜感激任何帮助,使这个功能更健壮。
【问题讨论】:
标签: c# stream filestream memorystream line-count