3

I have a SharePoint List to which I am adding new ListItems using the Client Object Model.

Adding ListItems is not a problem and works great.

How to add Attachments?

2 Answers 2

6

You can use below logic

List list = web.Lists.GetByTitle("listtitle");
ListItem item = list.GetItemById(1);
var attachment = new AttachmentCreationInformation();
attachment.FileName = "fileName";
attachment.ContentStream = new MemoryStream(System.IO.File.ReadAllBytes("streamFile"));
Attachment att = item.AttachmentFiles.Add(attachment);                                        
context.Load(att);                                     
context.ExecuteQuery();                        
3
using (var ctx = GetContext(webUri, userName, password))
{         
   var list = ctx.Web.Lists.GetByTitle(listTitle);
   var listItem = list.GetItemById(itemId);
   var attachment = listItem.SaveAttachment(filePath);
}

where

static class ListItemExtensions
{
    public static Attachment SaveAttachment(this ListItem item,string path)
    {
        var ctx = item.Context;
        var attachmentInfo = new AttachmentCreationInformation();
        attachmentInfo.FileName = System.IO.Path.GetFileName(path);
        using (var fs = new FileStream(path, FileMode.Open))
        {
            attachmentInfo.ContentStream = fs;
            var attachment =  item.AttachmentFiles.Add(attachmentInfo);
            ctx.ExecuteQuery();
            return attachment;
        }
    }

}


public static ClientContext GetContext(Uri webUri, string userName, string password)
{
    var securePassword = new SecureString();
    foreach (var ch in password) securePassword.AppendChar(ch);
    return new ClientContext(webUri) { Credentials = new SharePointOnlineCredentials(userName, securePassword) };
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.