Shwetha TO
Shwetha TO

Reputation: 1

Unable to see attachment name when I upload and attach the file to a work item through C# code

I have coded to attach the file to work item created, in C# using the Azure Devops REST API as shown here:

private void UploadAttachmentAsync(int workItemId, string destinationResultsLocation, string fitnesseDataTableName)
{
    string fi = System.IO.Directory.GetFiles(destinationResultsLocation).FirstOrDefault();

    var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fi));
    fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

    // Extract just the file name
    var fileName = Path.GetFileName(fi);
    fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = fileName,
        Name = "file"
    };

    // Upload the file to Azure DevOps
    string requestUrl = $"{OrganizationUrl}{ProjectName}/_apis/wit/attachments?api-version=7.0";
    HttpResponseMessage response =  client.PostAsync(requestUrl, fileContent).Result;

    if (response.IsSuccessStatusCode)
    {
        var jsonResponse =  response.Content.ReadAsStringAsync().Result;
        // Extract attachment URL from the response
        var jsonObject = JObject.Parse(jsonResponse);
        // Extract the URL from the response, which contains the attachment URL
        var attachmentUrl = jsonObject["url"].ToString();

        // Now, link the attachment to the work item
        LinkAttachmentToWorkItemAsync(workItemId, attachmentUrl, fileName);
    }
    else
    {
        Console.WriteLine("Error uploading attachment: " + response.StatusCode);
    }
}

private void LinkAttachmentToWorkItemAsync(int workItemId, string attachmenturl, string fileName)
{
    var jsonContent = new List<JsonPatchOperation>
         {
            new JsonPatchOperation
            {
                op = "add",
                path = "/relations/-",  // Add a new relation (attachment)
                value = new Relation
                {
                    rel = "AttachedFile",   // Define the type of relation (attachment)
                    url = attachmenturl,   // URL where the attachment is stored
                    displayName = fileName, // Display name of the attachment
                    attributes = new attributes
                    {
                        comment = $"Uploaded attachment: {fileName}" // Optional comment or description
                    }
                }
            }
    };

    var content = new StringContent(_serializer.Serialize(jsonContent), Encoding.UTF8, "application/json-patch+json");
    var response = client.PatchAsync($"{OrganizationUrl}{ProjectName}/_apis/wit/workitems/{workItemId}?api-version=7.1", content).Result;

    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("Attachment linked to work item successfully.");
    }
    else
    {
        Console.WriteLine("Error linking attachment to work item: " + response.StatusCode);  
    }
}   

I'm able to get the attachments linked to work item successfully and if I download the attachment, I could see the data. But the issue here is attachment is not showing the file name. When I download the file, the name will be the attachment ID. How do I get this working or is this not supported?

Upvotes: 0

Views: 48

Answers (1)

Bright Ran-MSFT
Bright Ran-MSFT

Reputation: 13944

When calling the API "Attachments - Create", you can use the optional parameter 'fileName' to specify the file name of the uploaded attachment on the request URI. If you do not specify the file name, it will use the attachment ID by default.

For example, set the file name as 'myAttachFile.txt' when uploading a text file as an attachment.

POST https://dev.azure.com/myOrg/myProject/_apis/wit/attachments?fileName=myAttachFile.txt&api-version=7.1

Once specified the file name on the request URI, from the response of the API call, the URL of the attachment will look like below.

{
    "id": "{attachmentId}",
    "url": "https://dev.azure.com/myOrg/{projectId}/_apis/wit/attachments/{attachmentId}?fileName=myAttachFile.txt"
}

Then, after linking this attachment to a work item using the URL, the file name of it will be displayed as 'myAttachFile.txt'.

Upvotes: 0

Related Questions