N.B.
N.B.

Reputation: 173

Create Azure DevOps attachment

I want to create a Azure DevOps Attachment. The attachment is an Outlook message. From the documentation seen here.

The body must be "[BINARY FILE CONTENT]". How can I read a .msg-File into C# and add it to a JsonBody Request?

Upvotes: 0

Views: 773

Answers (1)

Remco Brilstra
Remco Brilstra

Reputation: 828

Had to do something like this recently, the code looks like the stuff below.

The byte[] is the data i read directly from the filestream, like so

byte[] bytes;
using (var img = File.OpenRead("message.msg"))
{
    using (var memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        bytes = memoryStream.ToArray();
    }
}

then posting it to Azure DevOps

    internal async Task<Attachement> UploadAttachment(string filename,byte[] content)
    {

        ByteArrayContent data = new ByteArrayContent(content);

        HttpClient client = GetApiClient();

        using (HttpResponseMessage response = await client.PostAsync($"https://dev.azure.com/{_org}/_apis/wit/attachments?fileName={filename}&api-version=5.1", data))
        {
            // Parse response body en evaluate result
            var responseBody = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<Attachement>(responseBody);

        }
    }

This seems to work quit well for us :)

don't forget to also actually add it to the workitem using: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#add-an-attachment

Upvotes: 1

Related Questions