Search code examples
c#sharepoint-onlinefilestreamstreamreader

How To Monitor Download Progress of Stream


From SharePoint, I get a "Stream" for a file. I want to copy this entire file from the internet to a local file on the PC, but I want to have status while this download is occurring. How? FileStream and StreamReader seem to have bytes vs char differences when not doing a full "CopyTo" which doesn't have progress updates. There has to be a cleaner way...

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);
        }
    }
}


Solution

  • Just had to use BinaryReader instead of StreamReader. Easy Peasy.