Upload a document to a SharePoint list from Client

2019-01-30 12:02发布

问题:

I need to upload a document to a SharePoint list or folder using the Client Side Object Model from .NET (C#). What is the best way to do this?

The requirements are as follows:

  • Set metadata values

  • No limitation on file size

  • Must work with libraries that exceed the List View Threshold

回答1:

For Uploading Document to Sharepoint Document Library use Following function in Client Object Model:

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();
    }
}

Following link is Also Helpful For you 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



回答2:

Another way is to use the SaveBinaryDirect method. The SaveBinaryDirect method use Web Based Distributed Authoring and Versioning (WebDAV) for uploading and downloading files. Without building your own custom WCF service, WebDAV is the most efficient way to upload and download files.

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);


回答3:

Yet another option for uploading a file into a SharePoint site (including SharePoint Online) using File.SaveBinaryDirect Method:

/// <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);
      }
  }


回答4:

I found that the portion of delax post that updates new file attributes/columns will not work, here is another version that even wroks for a custom infopath library with promoted field:

   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;
    }


回答5:

I have worked out the following code, its working fine.

 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();
        }
    }

Thanks,

Sudhakar