逐行流文件并保持进度?

时间:2012-11-11 21:07:56

标签: c# winforms .net-4.0 filestream

我需要读取各种大小的文件,从1mb到2gb,因为文件可以有很大的尺寸,我正在流式传输。

  • 我如何知道有多少文件已被阅读并在不预先读取所有行的情况下跟踪它?

示例代码

int count = 0;
using (Stream stream = File.OpenRead(filename))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        string item = string.Empty;
        while ((item = reader.ReadLine()) != null)
        {
            item = item.Replace("\"", ""); // remove unwanted double quotes
            if (item.Length < 2) // dont need lines with less then 2 char
                continue;

            if (fine add to db) 
                count++; // to keep track of good lines
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您应该使用"Position""FileStream"覆盖的"Stream"属性。

查看here

答案 1 :(得分:0)

var remaining = yourFile.Length;
var goodLines = File.ReadLines(yourFile.FullName)
                    .Select(line => line.Replace("\"", ""))
                    .Where(line => line.Length > 1);

foreach(var goodLine in goodLines)
{
   // do something with goodLine

   // this will be slightly off since you remove quotes.
   remaining -= (goodLine.Length + Environment.NewLine.Length);
}

MSDN File.ReadLines