private static async Task DownloadFile()

in context/scripts/Web.cs [185:243]


        private static async Task<bool> DownloadFile(string name, string sourceUrl, string destinationFile)
        {
            Uri source = new Uri(sourceUrl);
            string host = source.DnsSafeHost;
            if (string.IsNullOrWhiteSpace(host))
            {
                throw new InvalidOperationException("Cannot get dns name for " + sourceUrl);
            }

            WriteLine("{0}\tresolving \"{1}\" by dns", name, source.DnsSafeHost);
            IPHostEntry hostInfo = await Dns.GetHostEntryAsync(host);
            foreach (var address in hostInfo.AddressList)
            {
                WriteLine("{0}\t address {1}", host, address);
            }

            using (WebClient client = new WebClient())
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                long lastPercent = -1;
                client.DownloadProgressChanged += (sender, args) =>
                    {
                        long percent = 100 * args.BytesReceived / args.TotalBytesToReceive;
                        if (percent % 5 == 0 && percent > lastPercent)
                        {
                            double speed = args.TotalBytesToReceive / 1024.0 / 1024.0 / stopwatch.Elapsed.TotalSeconds;
                            if (lastPercent == -1)
                            {
                                speed = 0;
                            }

                            lastPercent = percent;
                            WriteLine("\t{0}%\t{1}\t{2:0.0} MB/s", percent, name, speed);
                        }
                };

                bool completed = false;
                client.DownloadFileCompleted += (sender, args) =>
                {
                    completed = true;
                };

                try {
                    WriteLine("[Download file task] Trying to download the file [{0}] ...", destinationFile);
                    await client.DownloadFileTaskAsync(source, destinationFile);
                    return completed;
                } catch (Exception fileDownloadException) {
                    // Please, note that "AccessDenied"-related exception might occur in case of ...
                    // ... (1) FileSystem limitation - destination file couldn't be created / sub-folder does not exist;
                    // ... (2) Network limitation - host's network settings (proxy, local DNS) are blocking the file download;
                    while (fileDownloadException != null) {
                        WriteErrorLine(fileDownloadException.Message);
                        fileDownloadException = fileDownloadException.InnerException;
                    }
                    throw fileDownloadException;
                }
            }
        }