文件下载为 0 字节。如果调试它下载正确的文件

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

我正在尝试从 url 下载如下文件。如果调试代码文件下载成功 没有调试它给 0 字节 file.What 我在这里失踪了?

由于某些业务逻辑,我无法使用 Async

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);
    }
}

您可能遇到此问题,因为该方法在 CopyToAsync() 返回的任务完成之前退出。

要么让你的方法异步

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);
    }
}

或者使用同步方式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);
    }
}

如果您继续沿着同步路线前进,最好避免使用异步方法并找到 client.GetAsync() 的同步替代方法。