[英]How to read text file from memorystream without missing bytes
我正在编写一些代码来学习新的C#异步设计模式。 因此,我想编写一个小的Windows窗体程序,该程序可以计算文本文件的行数和单词数并显示阅读进度。
为避免磁盘交换,我将文件读入MemoryStream,然后构建一个StreamReader以按行和计数读取文本。
问题是我无法正确更新进度条。 我读了一个文件,但始终缺少字节,因此进度条无法完全填满。
需要帮助或想法来实现这一目标。 谢谢
public async Task Processfile(string fname)
{
MemoryStream m;
fname.File2MemoryStream(out m); // custom extension which read file into
// MemoryStream
int flen = (int)m.Length; // store File length
string line = string.Empty; // used later to read lines from streamreader
int linelen = 0; // store current line bytes
int readed = 0; // total bytes read
progressBar1.Minimum = 0; // progressbar bound to winforms ui
progressBar1.Maximum = flen;
using (StreamReader sr = new StreamReader(m)) // build streamreader from ms
{
while ( ! sr.EndOfStream ) // tried ( line = await sr.ReadLineAsync() ) != null
{
line = await sr.ReadLineAsync();
await Task.Run(() =>
{
linelen = Encoding.UTF8.GetBytes(line).Length; // get & update
readed += linelen; // bytes read
// custom function
Report(new Tuple<int, int>(flen, readed)); // implements Iprogress
// to feed progress bar
});
}
}
m.Close(); // releases MemoryStream
m = null;
}
分配给油轮的总长度包括每行的回车符。 ReadLineAsync()函数返回不包含回车符的字符串。 我的猜测是,进度栏中丢失的字节数与读取的文件中的回车数成正比。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.