无法使用CSOM将文件上载到文档库

时间:2015-10-15 16:02:05

标签: c# sharepoint asmx csom sharepointdocumentlibrary

我正在尝试将多个文件上传到文档库,并更新其coloumn值。 列表(Doc Lib)已经存在但我仍然遇到了uploadinf文件

我尝试过这些方法

  1. 使用lists.asmx

            NetworkCredential credentials = new NetworkCredential("user", "Pass", "domain");
            #region ListWebService
            ListService.Lists listService = new ListService.Lists();
            listService.Credentials = credentials;
            List list = cc.Web.Lists.GetByTitle(library);
            listService.Url = cc.Url + "/_vti_bin/lists.asmx";
            try
            {
                FileStream fStream = System.IO.File.OpenRead(filePath);
                string fName = fStream.Name.Substring(3);
                byte[] contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                fStream.Close();
    
                string attach = listService.AddAttachment(library, itemId.ToString(), Path.GetFileName(filePath), contents);
    
            }
            #endregion
    
    
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                CSVWriter("Message:\n" + ex.Message + "\nDetail:\n" +
                    ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace, LogReport);
            }
    
  2. ServerException :To add an item to a document library, use SPFileCollection.Add()

    上出现错误AddAttachment()
    1. 使用

              List lib = cc.Web.Lists.GetByTitle("TestLib");
               FileCreationInformation fileInfo = new FileCreationInformation();
               fileInfo.Content = System.IO.File.ReadAllBytes("C:\\Users\\AJohn\\Desktop\\sample.docx");
               fileInfo.Url = "https://serverm/sites/Testing1/TestLib/sample.docx";
               fileInfo.Overwrite = true;
               Microsoft.SharePoint.Client.File upFile = lib.RootFolder.Files.Add(fileInfo);
               cc.Load(upFile);
               cc.ExecuteQuery();
      
    2. 我可以使用此方法上传once,但现在我在ServerException :To add an item to a document library, use SPFileCollection.Add()上获得了cc.ExecuteQuery()

      但是,如果这个方法有效,我想要的是我应该更新与该文件相关的coloumn值。在第一种方法中,我得到item.ID,因此我可以更新Coloumn值

1 个答案:

答案 0 :(得分:2)

关于第二种方法,以下示例演示了如何将文件上传到文档库并设置其属性(例如Category文本字段)

using (var ctx = new ClientContext(webUri))
{
     var targetList = ctx.Web.Lists.GetByTitle("Documents");
     var fileInfo = new FileCreationInformation
     {
          Url = System.IO.Path.GetFileName(sourcePath),
          Content = System.IO.File.ReadAllBytes(sourcePath),
          Overwrite = true
     };

     var file = targetList.RootFolder.Files.Add(fileInfo);
     var item = file.ListItemAllFields;
     item["Category"] = "User Guide";
     item.Update();
     ctx.ExecuteQuery();
}