calculating hashes on-the-fly during download

Viewed 1049

I have the following code that does download a file from the internet and saves it somewhere:

class Foo
{
    private static Uri _url;
    private static string _filepath;
    public static void Main(string[] args)
    {
        _url = new Uri("http://www.speedtest.qsc.de/1MB.qsc");
        _filepath = Environment.CurrentDirectory + "/" + Path.GetFileName(_url.LocalPath);
        using (var wc = new WebClient())
        {                
            wc.DownloadFileCompleted += _bar;
            wc.DownloadFileAsync(_url, _filepath);               
        }
        Console.ReadKey();
    }

    private static void _bar (object sender, AsyncCompletedEventArgs e)
    {
        using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead(_filepath))
            {
                md5.ComputeHash(stream);
                Environment.Exit(0);
            }
        }
    }
}

I’d like to compute MD5 and SHA1 for the file. I can do that easily by opening a FileStream after the download has completed and use that to compute the hash. However, that is quite inefficient for large files at least.

What I really would like to do is to calculate them already during download by updating the hash after a new block of bytes has been retrieved (with TransformBlock method).

Is there some event of WebClient I can subscribe to, to get the byte blocks and then update both hashes? Should I use some other class like WebRequest? I need the total number of bytes to read too in order to display some download progress information.

Thanks!

1 Answers
Related