'File downloading as 0 byte. If debug it download correct file

I am trying to download file as below from a url. If debug the code the file download successfully Without debug it give 0 byte file.What I am missing here?

I cannot use Async because of certain business logic

public  void download_attachments(string file_id)
{
    var client = new HttpClient();
    var response = client.GetAsync(@"https://xxxxxxxxxx/api/Attachments/DownloadAttachment/" + file_id).Result;
    
    using (var fs = new FileStream(@"C:\d\"+ Regex.Replace(response.Content.Headers.ContentDisposition.FileName, @"(\[|""|\])", ""), FileMode.CreateNew))
    {
        response.Content.CopyToAsync(fs);
    }
}


Solution 1:[1]

You are likely having this problem because the method exits before the task returned by CopyToAsync() completes.

Either make your method asynchronous

public async Task download_attachments(string file_id)
{
    var client = new HttpClient();
    var response = await client.GetAsync(@"https://xxxxxxxxxx/api/Attachments/DownloadAttachment/" + file_id);
    // WARNING: potential directory traversal vulnerability
    using (var fs = new FileStream(@"C:\d\"+ Regex.Replace(response.Content.Headers.ContentDisposition.FileName, @"(\[|""|\])", ""), FileMode.CreateNew))
    {
        await response.Content.CopyToAsync(fs);
    }
}

or use the synchronous method CopyTo().

public void download_attachments(string file_id)
{
    var client = new HttpClient();
    var response = client.GetAsync(@"https://xxxxxxxxxx/api/Attachments/DownloadAttachment/" + file_id).Result;
    // WARNING: potential directory traversal vulnerability
    using (var fs = new FileStream(@"C:\d\"+ Regex.Replace(response.Content.Headers.ContentDisposition.FileName, @"(\[|""|\])", ""), FileMode.CreateNew))
    {
        response.Content.CopyTo(fs, null, default);
    }
}

If you continue down the synchronous route, it would be best to avoid use of Async methods and find a synchronous alternative to client.GetAsync().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1