The remote server returned an error: (409) Conflict from SharePoint ClientObjectModel

Problem

I got this issue for ListItem having attachments. We’re initially creating a ListItem using the Update() & ExecuteQuery() method. Next when we tried to create an attachment for the same ListItem using ExecuteQuery(), this error was thrown.

Solution

Solution was to remove the ExecuteQuery() after the ListItem Update() and use a single ExecuteQuery() for both the ListItem and its Attachment.

using System;
using IO = System.IO;
using System.Linq;
using System.Runtime.Remoting;
using System.Text;
using System.Threading;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;


string siteUrl = "http://servername:12345/";
SP.ClientContext ctx = new SP.ClientContext(siteUrl);
SP.List list = ctx.Web.Lists.GetByTitle("ListTitle");

SP.ListItemCreationInformation listItemCreationInfo = new SP.ListItemCreationInformation();
SP.ListItem oListItem = list.AddItem(listItemCreationInfo);
                
//This will create ListItem before adding attachments
oListItem.Update();

//The following line should be removed
//ctx.ExecuteQuery();


string strFilePath = "FullFilePath";

byte[] bytes = IO.File.ReadAllBytes(strFilePath);

using (IO.MemoryStream mStream = new IO.MemoryStream(bytes))
{
    SP.AttachmentCreationInformation aci = new SP.AttachmentCreationInformation();
    aci.ContentStream = mStream;
    aci.FileName = IO.Path.GetFileNameWithoutExtension(strFilePath);

    oListItem.AttachmentFiles.Add(aci);

    oListItem.Update();
    ctx.ExecuteQuery();
}

The error was thrown at the last line (ctx.ExecuteQuery() in bold). Actually the List was already created above (commented ctx.ExecuteQuery()). The solution was to remove that ExecuteQuery() and bundle both the requests, create ListItem & upload attachment, in a single ExecuteQuery().

NOTE:- Do not forget to mention the oListItem.Update() as the ListItem has to be created first before adding attachments to it. Just don’t immediately call the Execute method