public static void DownloadFile(string destFileName, Stream responseStream, CancellationToken?token = null, Action <int> indicateProgress = null) { using (new ProfileSection("Download file", typeof(WebRequestHelper))) { ProfileSection.Argument("destFileName", destFileName); ProfileSection.Argument("responseStream", responseStream); ProfileSection.Argument("token", token); ProfileSection.Argument("indicateProgress", indicateProgress); int bufferSize = Settings.CoreWebDownloadBufferSize.Value; using (var fileStream = new FileStream(destFileName, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize)) { var buffer = new byte[bufferSize]; while (true) { if (token != null) { ((CancellationToken)token).ThrowIfCancellationRequested(); } int count = responseStream.Read(buffer, 0, bufferSize); if (count == 0) { break; } fileStream.Write(buffer, 0, count); if (indicateProgress != null) { indicateProgress(count); } } } } }