Add File Attachment to SharePoint List Item

I finally gave up on trying to use native UiPath activities and went with Invoke Code. It is working for me so far to attach items to an existing SharePoint list item.

Here’s the C# code I’m using:

var fileName = System.IO.Path.GetFileName(in_FilePath);
var endpointUrl = string.Format("{0}/_api/web/lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')",in_WebUri,in_ListTitle,in_ItemId,fileName);

System.Net.Http.WinHttpHandler handler = new System.Net.Http.WinHttpHandler();
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler);

client.DefaultRequestHeaders.Add("X-RequestDigest", in_FormDigest);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", in_AccessToken);
using (var stream = System.IO.File.OpenRead(in_FilePath))
	{
		var response =  client.PostAsync(endpointUrl, new System.Net.Http.StreamContent(stream)).Result;
		out_APIResponseHeaders = response.Headers;
		out_APIResponseContent = response.Content;
		out_APIResponseStatusCode = response.StatusCode;
		out_APIResponseIsSuccessful = response.IsSuccessStatusCode;
		}

Here’s the arguments I’m using with that code:
image

  • in_FilePath is the path to the file you want to attach.
  • in_WebUri is the URL of the site that contains the list you want to modify E.G. https://(yourtenant).sharepoint.com/IT/Team/
  • in_ListTitle is the SharePoint list name
  • in_ItemId is the id of the list item. This should be a number (yes, I’m passing it as a string. Bad me. :slight_smile: )
  • in_FormDigest. This one’s harder. You have to make a post request to https://(yourtenant).sharepoint.com/_api/contextinfo. If done successfully, you’ll get a FormDigestValue in the response.
  • in_AccessToken This is an authorization bearer token for the api call. You get this from a POST to https://accounts.accesscontrol.windows.net//tokens/OAuth/2 I followed this site to figure it out Inside SharePoint 2013 OAuth Context Tokens | Microsoft Learn
1 Like