views:

153

answers:

2

Hello -

I have created some code to create a list item programmatically. Now I would like to attach a file to the list. I'm getting a 401 error: unauthorized. I have set the credentials which works for creating the item but not attaching the file. Any ideas?

Dim credentials As New System.Net.NetworkCredential(MyUser, MyPassword, MyDomain)

Dim SiteUrl As String = MyUrl
Dim clientContext As New ClientContext(SiteUrl)

clientContext.Credentials = credentials

Dim list As List = clientContext.Web.Lists.GetByTitle(MyList)
Dim itemCreateInfo As New ListItemCreationInformation()
Dim listItem As Microsoft.SharePoint.Client.ListItem = list.AddItem(itemCreateInfo)

listItem("Title") = "Test Programmatically Create Item"
listItem("Subject") = "TEST"
listItem("Class") = "101"
listItem("Section") = "20"
listItem.Update()

listItem.Update()
clientContext.ExecuteQuery()

Dim fStream As Stream = File1.PostedFile.InputStream                
Dim attachmentPath As String = String.Format("/{0}/Lists/{1}/Attachments/{2}/{3}", MySite, MyList, listItem.Id, MyFileName)                

'-- This Line Fails with the following error
'-- The remote server returned an error: (401) Unauthorized.               
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, attachmentPath, fStream, True)

I know setting the credentials is correct because if I don't set them then I get this error trying to create the list item.

Any thoughts are greatly appreciated or if there is a better way to attach a file to a list item please let me know.

Thanks!

A: 

Take a look at the following link. This should point you in the right direction.

http://www.sharepointdevwiki.com/display/public/Creating+a+List+Item+instance+programmatically+using+the+object+model?focusedCommentId=7897226

You could also take a look at SPSecurity.RunWithElevatedPrivileges().

Good luck

A: 

Thanks but the examples in the link you provided use the server side object model which isn't going to help me since this application is running on a different server then our sharepoint instance.

What I ended up doing was creating a web reference to lists.asmx and then I'm able to call AddAttachment through the web service and that works remotely. It would be nice if the SP 2010 client OM had this functionality built in but this will suffice for now.

Greg