0

Would you please provide a code sample on how to add attachments (text file and an image) to an existing work item in Azure DevOps using C#.

Nick
  • 780
  • 2
  • 13
  • 33
  • Here's the REST API for attachment: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-server-rest-5.0 and here's some C# samples: https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/rest/samples?view=azure-devops – Amittai Shapira Jul 24 '19 at 21:19
  • Thank you Amittai. I am able to connect to Azure DevOps and upload the file using the following code but I am not sure how to attach it to a workitem using POST as the sample from the link you sent. AttachmentReference attachment = workItemTrackingHttpClient.CreateAttachmentAsync(@"C:\TestDocument.txt").Result; – Nick Jul 24 '19 at 21:49
  • 2
    @Nick edit your question with the code you tried and what exactly you didn't success – Shayki Abramczyk Jul 25 '19 at 07:07

1 Answers1

6

Here are some blog and cases: 1 . 2 with C# code samples, you can refer to them.

using (FileStream attStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{
    var att = WitClient.CreateAttachmentAsync(attStream, filePathSplit[filePathSplit.Length – 1]).Result; // upload the file
    
    JsonPatchDocument patchDocument = new JsonPatchDocument();
    
    patchDocument.Add(new JsonPatchOperation()
    {
        Operation = Operation.Add,
        Path = "/relations/-",
        Value = new
        {
            rel = "AttachedFile",
            url = att.Url,
            attributes = new { comment = “Comments for the file “ + filePathSplit[filePathSplit.Length – 1] }
        }
    });

    var workItem = UpdateWorkItemAsync(patchDocument, workItemId).Result;
}
fubaar
  • 2,489
  • 1
  • 21
  • 21
Hugh Lin
  • 17,829
  • 2
  • 21
  • 25