reading a large download is two steps
- read the headers. this is where the status code 200 (OK) read
- stream the body. in a large download this can easily fail due to any network error.
you have rather convoluted code. you seem to create a task for no reason, return a new task with the stream. convert an async call into sync, why not simple:
var zipPathForFolderOrPathForFile = string.Empty;
var container = new Bootstrapper().Bootstrap();
Constants.RequestBaseAddress = LoginConfigurations.GetInstance().Portal;
IAutomationApiClient automationApiClient = container.Resolve<IAutomationApiClient>();
// start fetch
var (contentStream, fileNameResults) = await automationApiClient.PostDownloadFiles($"{LoginConfigurations.GetInstance().Portal}/api/HandleFiles/PostDownloadFiles", SelectedPathItem.Value, sbFilesIdentifiers.ToString(), true, LoginConfigurations.GetInstance().SessionToken);
if (contentStream == null || string.IsNullOrEmpty(fileNameResults))
{
_logger.Error($"No data return from download for identiffiers:{sbFilesIdentifiers}");
return;
}
// zip file path
zipPathForFolderOrPathForFile = Path.Combine(
SelectedItem.Path == null
? SelectedItem.Name.TrimEnd('\\').TrimEnd('\\')
: SelectedItem.Path, fileNameResults
);
// Create the file stream in destination
var fileStream = File.Create(zipPathForFolderOrPathForFile);
// fetch file data from server and copy to filestream
await contentStream.CopyToAsync(fileStream);
// these should be in a finally block
fileStream.Dispose();
contentStream.Dispose();