Thursday, June 17, 2010

SharePoint 2010 Client Object Model, attachment creation

Unfortunately SCOM doesn't support attachment creation. It doesn't have any API which allows to create attachments if item has no attachment already.

Microsoft recommends to use Lists.asmx SharePoint web service if you need to create attachment remotely. Or create own WCF service in the SharePoint context.

If item already has attachments (at least one) you can add new attachments with using next approach:

using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System.IO;

public static void AddListItemAttachment(string attachFilePath, string listUrl, string itemId)
{
ClientContext clientContext = new ClientContext(listUrl);
Uri url = new Uri(listUrl);

using (FileStream strm = new FileInfo(attachFilePath).Open(FileMode.Open))
{
var attachUrl = url.AbsolutePath + "/Attachments/" + itemId + "/" + Path.GetFileName(attachFilePath);
SP.File.SaveBinaryDirect(clientContext, attachUrl, strm, true);
}
}

This method is based on the knowledge that SharePoint stores item attachments in the special folder with path: ListURL+"/Attachments/" + itemID.
But I didn't find a way to create this folder if it doesn't exist so this method works only if folder exists already (it means that item has at least 1 attachment already). Usual way for folder creation by SCOM doesn't work in this case(with error "Unable to complete action").

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.