SharePoint 2010 - Client Object Model - Add attachment to ListItem
http://msdn.microsoft.com/en-us/library/websvclists.lists.addattachment.aspx
http://stackoverflow.com/questions/2969810/sharepoint-2010-client-object-model-add-attachment-to-listitem
I struggled for a long time with this problem too, so I thought I'd post a complete code sample showing how to successfully create a list item and add an attachment.
I am using the Client Object API to create the list item, and the SOAP web service to add the attachment. This is because, as noted in other places on the web, the Client Object API can only be used to add attachments to an item where the item's upload directory already exists (eg. if the item already has an attachment). Else it fails with a 409 error or something. The SOAP web service copes with this OK though.
Note that another thing I had to overcome was that even though I added the SOAP reference using the following URL:
The URL that VS actually added to the app.config was:
I had to manually change the app.config back to the correct URL, else I would get the error:
List does not exist. The page you selected contains a list that does not exist. It may have been deleted by another user. 0x82000006
Here is the code:
void CreateWithAttachment()
{
const string listName = "CodeReviews";
// set up our credentials
var credentials = new NetworkCredential("username", "password", "domain");
// create a soap client
var soapClient = new ListsService.Lists();
soapClient.Credentials = credentials;
// var create a client context
var clientContext = new Microsoft.SharePoint.Client.ClientContext("https://my.sharepoint.installation/personal/test");
clientContext.Credentials = credentials;
// create a list item
var list = clientContext.Web.Lists.GetByTitle(listName);
var itemCreateInfo = new ListItemCreationInformation();
var newItem = list.AddItem(itemCreateInfo);
// set its properties
newItem["Title"] = "Created from Client API";
newItem["Status"] = "New";
newItem["_Comments"] = "here are some comments!!";
// commit it
newItem.Update();
clientContext.ExecuteQuery();
// load back the created item so its ID field is available for use below
clientContext.Load(newItem);
clientContext.ExecuteQuery();
// use the soap client to add the attachment
const string path = @"c:\temp\test.txt";
soapClient.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(path),
System.IO.File.ReadAllBytes(path));
}
Hope this helps someone.
http://msdn.microsoft.com/en-us/library/websvclists.lists.addattachment.aspx
http://stackoverflow.com/questions/2969810/sharepoint-2010-client-object-model-add-attachment-to-listitem
댓글 없음:
댓글 쓰기