0

I was trying to download work item attachment from devops using the REST API. The file is downloading, but file name and extension are not correct and I'm unable to open after downloading the file.

var personalaccesstoken = "";
var DeserializedClass = new List<Responcejson>();
string bseurl = "https://xxx/_apis/wit/attachments/xxxx-0cdb-4f53-9785-55d642d603e7?fileName=abc.png&download=true&api-version=5.0";

try
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                    Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                            string.Format("{0}:{1}", "", personalaccesstoken))));

        using (HttpResponseMessage response = await client.GetAsync(bseurl))
        {
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            //JObject data = JObject.Parse(responseBody);
            return responseBody;
        }
    }
}
catch (Exception ex)
{
    return ex.ToString();
}

but this downloads the file as "Devops" with no filename and extension....

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
reckeyba
  • 5
  • 2
  • you already seem to know the filename because it's in the URL you're sending, so why not just use that? P.S. you seem to be trying to download an image file as text, which is unlikely to work very well, since images are binary data. https://stackoverflow.com/questions/45711428/download-file-with-webclient-or-httpclient might help you – ADyson Dec 07 '20 at 13:53
  • You need to set the [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header on the response. If Azure Devops provite it, you can return it from the request. – ESG Dec 07 '20 at 13:56
  • Side note on your usage of HttpClient: It should not be created/disposed like that. See why here: https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed-between-requests – ESG Dec 07 '20 at 13:57

1 Answers1

0

When executing the Azure DevOps REST API "Downloads an attachment", you can use the Media Types "application/octet-stream" or "application/zip". See here.

I noticed this in your code,

string responseBody = await response.Content.ReadAsStringAsync();

If the attachment is image, this may cause issues.

In addition, there is the corresponding client API you can directly use in your C# code. See "WorkItemTrackingHttpClientBase.GetAttachmentContentAsync Method".

Bright Ran-MSFT
  • 5,190
  • 1
  • 5
  • 12