SP 2010附加文件客户端对象模型

时间:2010-09-15 14:04:24

标签: sharepoint sharepoint-2010

我已经创建了一些代码来以编程方式创建列表项。现在我想将一个文件附加到列表中。我收到401错误:未经授权。我设置了用于创建项目但不附加文件的凭据。有什么想法吗?

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)

我知道设置凭据是正确的,因为如果我没有设置它们,那么我会在尝试创建列表项时遇到此错误。

非常感谢任何想法,或者如果有更好的方法将文件附加到列表项目,请告诉我。

谢谢!

2 个答案:

答案 0 :(得分:1)

它对我有用。 我首先读取需要上传到内存中的文件,并使用MemoryStream将文件传递给SaveBinaryDirect。

    static void  moveFileFromOneFarmToAnother()
   {

        string srcSiteUrl = "SourceSiteUrl";
        string srcFileRelUrl = "ReletiveUrlOfTheListItemAttachment";
        ClientContext srcCC = new ClientContext(srcSiteUrl);
        Web srcWb = srcCC.Web;
        srcCC.Load(srcWb, w => w.ServerRelativeUrl);
        srcCC.ExecuteQuery();
        FileInformation fI = Microsoft.SharePoint.Client.File.OpenBinaryDirect(srcCC, srcWb.ServerRelativeUrl + srcFileRelUrl);
        byte[] buffer = new byte[16 * 1024];
        byte[] byteArr;
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = fI.Stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            byteArr = ms.ToArray();
        }
        MemoryStream mnm = new MemoryStream(byteArr);
        srcCC.ExecuteQuery();
        string desSiteUrl = "DestinationSiteUrl";
        string desFileUrl = "ReletiveUrlOfTheListItemAttachment";
        ClientContext cc = new ClientContext(desSiteUrl);
        Web wb = cc.Web;
        cc.Load(wb, w1 => w1.ServerRelativeUrl);
        cc.ExecuteQuery();
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(cc, wb.ServerRelativeUrl + desFileUrl, mnm, true);
        cc.ExecuteQuery();
   }

答案 1 :(得分:0)

看看以下链接。这应该指向正确的方向。

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

您还可以查看SPSecurity.RunWithElevatedPrivileges()。

祝你好运