如何监控流的下载进度
How To Monitor Download Progress of Stream
我从 SharePoint 获得文件的“流”。我想将整个文件从 Internet 复制到 PC 上的本地文件,但我想在下载过程中获得状态。如何? FileStream 和 StreamReader 在不执行没有进度更新的完整“CopyTo”时似乎存在字节与字符差异。必须有更清洁的方法...
using (var sr = new StreamReader(fileData.Value))
{
using (FileStream fs = new FileStream(localFile + "_tmp", FileMode.Create))
{
byte[] block = new byte[1024];
// only guessing something like this is necessary...
int count = (int)Math.Min(sr.BaseStream.Length - sr.BaseStream.Position, block.Length);
while (sr.BaseStream.Position < sr.BaseStream.Length)
{
// read requires char[]
sr.Read(block, 0, count);
// write requires byte[]
fs.Write(block, 0, count);
Log("Percent complete: " + (sr.BaseStream.Position / sr.BaseStream.Length));
count = (int)Math.Min(sr.BaseStream.Length - sr.BaseStream.Position, block.Length);
}
}
}
只需要使用 BinaryReader 而不是 StreamReader。轻松愉快。
我从 SharePoint 获得文件的“流”。我想将整个文件从 Internet 复制到 PC 上的本地文件,但我想在下载过程中获得状态。如何? FileStream 和 StreamReader 在不执行没有进度更新的完整“CopyTo”时似乎存在字节与字符差异。必须有更清洁的方法...
using (var sr = new StreamReader(fileData.Value))
{
using (FileStream fs = new FileStream(localFile + "_tmp", FileMode.Create))
{
byte[] block = new byte[1024];
// only guessing something like this is necessary...
int count = (int)Math.Min(sr.BaseStream.Length - sr.BaseStream.Position, block.Length);
while (sr.BaseStream.Position < sr.BaseStream.Length)
{
// read requires char[]
sr.Read(block, 0, count);
// write requires byte[]
fs.Write(block, 0, count);
Log("Percent complete: " + (sr.BaseStream.Position / sr.BaseStream.Length));
count = (int)Math.Min(sr.BaseStream.Length - sr.BaseStream.Position, block.Length);
}
}
}
只需要使用 BinaryReader 而不是 StreamReader。轻松愉快。