Handle ListItem attachments via CSOM
-
20-12-2020 - |
Question
I'm able to add OR remove attachments to/from a ListItem:
Remove
foreach (Attachment a in emailItem.AttachmentFiles)
{
a.DeleteObject();
}
emailItem.Update();
ctx.ExecuteQuery();
Add
foreach (AttachmentFile file in data.NewAttachments)
{
var attInfo = new AttachmentCreationInformation();
attInfo.FileName = "Name";
attInfo.ContentStream = new MemoryStream(theBytes);
emailItem.AttachmentFiles.Add(attInfo);
}
emailItem.Update();
ctx.ExecuteQuery();
But when I combine them I get a conflict error when ctx.ExecuteQuery();
is called:
foreach (Attachment a in emailItem.AttachmentFiles)
{
a.DeleteObject();
}
emailItem.Update();
foreach (AttachmentFile file in data.NewAttachments)
{
var attInfo = new AttachmentCreationInformation();
attInfo.FileName = "Name";
attInfo.ContentStream = new MemoryStream(theBytes);
emailItem.AttachmentFiles.Add(attInfo);
}
emailItem.Update();
ctx.ExecuteQuery();
I also tried to remove the first call to emailItem.Update();
but get the same error. I know I could split the code in two parts by reloading the item, but it would be generate two versions of it since it would get saved twice...don't think it is a nice solution.
Does somebody have a hint?
Solution
Please use below code:
foreach (AttachmentFile file in data.NewAttachments)
{
var attInfo = new AttachmentCreationInformation();
attInfo.FileName = "Name";
attInfo.ContentStream = new MemoryStream(theBytes);
emailItem.AttachmentFiles.Add(attInfo);
}
emailItem.Update();
foreach (Attachment a in emailItem.AttachmentFiles)
{
a.DeleteObject();
}
emailItem.Update();
ctx.ExecuteQuery();
Hope it works for you.
OTHER TIPS
Thanks to @Samir Khimani for the help, however the deleting of the attachments does not always work since it modifies the current iteration. I edited a little bit his answer followings:
bool update = false;
int oldFiles = item.AttachmentFiles == null || item.AttachmentFiles.Count == 0 ? 0 : item.AttachmentFiles.Count;
if (myData.NewAttachments != null && myData.NewAttachments.Length > 0)
{
foreach (AttachmentFile file in myData.NewAttachments)
{
var attInfo = new AttachmentCreationInformation();
attInfo.FileName = file.Name;
attInfo.ContentStream = new MemoryStream(theBytes);
item.AttachmentFiles.Add(attInfo);
}
update = true;
}
if (myData.AttachmentsToRemove != null && myData.AttachmentsToRemove.Length > 0)
{
for (int i = oldFiles-1; i >= 0; i--)
{
Attachment a = item.AttachmentFiles[i];
if (myData.AttachmentsToRemove.Contains(a.FileName))
{
a.DeleteObject();
update = true;
}
}
}
if (update)
{
item.Update();
ctx.ExecuteQuery();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange