从客户端对象模型将文档上载到SharePoint列表

时间:2012-03-24 00:01:16

标签: sharepoint file-upload

我需要使用.NET(C#)中的客户端对象模型将文档上载到SharePoint列表或文件夹。做这个的最好方式是什么?

要求如下:

  • 设置元数据值

  • 文件大小没有限制

  • 必须使用超出列表视图阈值的库

5 个答案:

答案 0 :(得分:20)

对于将文档上载到Sharepoint文档库,请在客户端对象模型中使用以下函数:

public void UploadDocument(string siteURL, string documentListName, string documentListURL, string documentName, byte[] documentStream)
{
    using (ClientContext clientContext = new ClientContext(siteURL))
    {
        //Get Document List
        List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);

        var fileCreationInformation = new FileCreationInformation();
        //Assign to content byte[] i.e. documentStream

        fileCreationInformation.Content = documentStream;
        //Allow owerwrite of document

        fileCreationInformation.Overwrite = true;
        //Upload URL

        fileCreationInformation.Url = siteURL + documentListURL + documentName;
        Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
            fileCreationInformation);

        //Update the metadata for a field having name "DocType"
        uploadFile.ListItemAllFields["DocType"] = "Favourites";

        uploadFile.ListItemAllFields.Update();
        clientContext.ExecuteQuery();
    }
}

以下链接对您也有帮助 1)http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx

2)http://msdn.microsoft.com/en-us/library/ee956524.aspx

3)http://www.codeproject.com/Articles/103503/How-to-upload-download-a-document-in-SharePoint-20

答案 1 :(得分:14)

另一种方法是使用SaveBinaryDirect方法。 SaveBinaryDirect方法使用基于Web的分布式创作和版本控制(WebDAV)来上载和下载文件。如果不构建自己的自定义WCF服务,WebDAV是上传和下载文件的最有效方式。

using (FileStream fs = new FileStream(FileToImport, FileMode.OpenOrCreate))
{
   Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, uri.LocalPath, fs, true);
}
Microsoft.SharePoint.Client.File newFile = web.GetFileByServerRelativeUrl(uri.LocalPath);
context.Load(newFile);
context.ExecuteQuery();

//check out to make sure not to create multiple versions
newFile.CheckOut();

ListItem item = newFile.ListItemAllFields;
item["Created"] = info.SourceFile.CreationTime;
item["Modified"] = info.SourceFile.LastWriteTime;
item.Update();

// use OverwriteCheckIn type to make sure not to create multiple versions 
newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);

答案 2 :(得分:8)

使用File.SaveBinaryDirect Method将文件上载到SharePoint网站(包括SharePoint Online)的另一种选择:

/// <summary>
/// Uploads the specified file to a SharePoint site
/// </summary>
/// <param name="context">SharePoint Client Context</param>
/// <param name="listTitle">List Title</param>
/// <param name="fileName">File Name</param>
private static void UploadFile(ClientContext context, string listTitle,string fileName)
{
     using (var fs = new FileStream(fileName, FileMode.Open))
     {
          var fi = new FileInfo(fileName);
          var list = context.Web.Lists.GetByTitle(listTitle);
          context.Load(list.RootFolder);
          context.ExecuteQuery();
          var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);

          Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
      }
  }

答案 3 :(得分:6)

我发现更新新文件属性/列的delax post部分不起作用,这是另一个版本甚至为具有提升字段的自定义infopath库冒险:

   public string AddNewForm(string WebUrl, string NewTitle)
    {
        string strMsg = "";
        if (string.IsNullOrEmpty(WebUrl))
            return EmptyProcURL;

        try
        {
            // Starting with ClientContext, the constructor requires a URL to the server running SharePoint. 
            using (ClientContext client = new ClientContext(WebUrl))
            {
                //client.Credentials = System.Net.CredentialCache.DefaultCredentials;

                // Assume that the web site has a library named "FormLibrary". 
                var formLib = client.Web.Lists.GetByTitle("FormLibrary");
                client.Load(formLib.RootFolder);
                client.ExecuteQuery();

                // FormTemplate path, The path should be on the local machine/server !
                string fileName = @"D:\Projects\FormTemplate.xml"; 

                var fileUrl = "";

                //Craete FormTemplate and save in the library.
                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    var fi = new FileInfo("newForm.xml");
                    fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
                }

                // Get library columns collection.
                var libFields = formLib.Fields;
                client.Load(libFields);
                client.ExecuteQuery();

                Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);

                ListItem item = newFile.ListItemAllFields;

                // Here the index of Title column is 9, you may use this format to update any column (even promoted fields).
                // To find the index of interested column you should inspect libFields at debug mode, look in the libFields.Fields collection to find the index!
                item[libFields[9].StaticName] = NewTitle ;
                item.Update();
                client.ExecuteQuery();
            }
        }
        catch (Exception ex)
        {
            strMsg = ex.Message;
        }

        return strMsg;
    }

答案 4 :(得分:1)

我已经制定了以下代码,可以正常工作。

 static void Main(string[] args)
    {
       try
        { 
         using (ClientContext client = new ClientContext("https://sharepoint2018/sites/demos"))
            {                   
                string passWd = "password";
                SecureString securePassWd = new SecureString();
                foreach (var c in passWd.ToCharArray())
                {
                    securePassWd.AppendChar(c);
                }
                client.Credentials = new SharePointOnlineCredentials("username", securePassWd);
                var formLib = client.Web.Lists.GetByTitle("Documents");
                client.Load(formLib.RootFolder);
                client.ExecuteQuery();
                string fileName = @"C:\demo.txt";  // FilePath
                var fileUrl = "";  
                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    var fi = new FileInfo("demo.txt"); //file Title  
                    fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
                    client.ExecuteQuery();
                }  
                var libFields = formLib.Fields;
                client.Load(libFields);
                client.ExecuteQuery();
                Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);
                ListItem item = newFile.ListItemAllFields;
                item.Update();
                client.ExecuteQuery();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.ReadKey();
        }
    }

谢谢

Sudhakar