How to download/upload files from/to SharePoint 2013 using CSOM?

后端 未结 8 2131
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 20:19

I am developing a Win8 (WinRT, C#, XAML) client application (CSOM) that needs to download/upload files from/to SharePoint 2013.

How do I do the Download/Upload?

相关标签:
8条回答
  • 2020-11-30 21:03

    A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .

    https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/

    The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.

    using System;
    using System.IO;
    using System.Linq;
    using System.Web;
    using Microsoft.SharePoint.Client;
    using System.Security;
    
    using ClientOM = Microsoft.SharePoint.Client;
    
    namespace MvcApplication.Models.Home
    {
        public class SharepointModel
        {
            public ClientContext clientContext { get; set; }
            private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
            private string LibraryUrl = "Shared Documents/Invoices/";
            private string UserName = "someone.surname@somecompany.com";
            private string Password = "********";
            private Web WebClient { get; set; }
    
            public SharepointModel()
            {
                this.Connect();
            }
    
            public void Connect()
            {
                try
                {
                    using (clientContext = new ClientContext(ServerSiteUrl))
                    {
                        var securePassword = new SecureString();
                        foreach (char c in Password)
                        {
                            securePassword.AppendChar(c);
                        }
    
                        clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
                        WebClient = clientContext.Web;
                    }
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
    
            public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
            {
                try
                {
                    HttpPostedFileBase file = null;
                    for (int f = 0; f < Request.Files.Count; f++)
                    {
                        file = Request.Files[f] as HttpPostedFileBase;
    
                        string[] SubFolders = LibraryUrl.Split('/');
                        string filename = System.IO.Path.GetFileName(file.FileName);
                        var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
                        file.SaveAs(path);
    
                        clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
                        clientContext.ExecuteQuery();
    
                        //https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
                        List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
                        clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
                        clientContext.ExecuteQuery();
    
                        string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
                        var folderToBindTo = documentsList.RootFolder.Folders;
                        var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();
    
                        var fileCreationInformation = new FileCreationInformation();
                        //Assign to content byte[] i.e. documentStream
                        fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
                        //Allow owerwrite of document
                        fileCreationInformation.Overwrite = true;
                        //Upload URL
                        fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;
    
                        Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
    
                        //Update the metadata for a field having name "DocType"
                        uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";
    
                        uploadFile.ListItemAllFields.Update();
                        clientContext.ExecuteQuery();
                    }
    
                    return "";
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
    
            public string DownloadFiles()
            {
                try
                {
                    string tempLocation = @"c:\Downloads\Sharepoint\";
                    System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
    
                    FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
                    clientContext.Load(files);
                    clientContext.ExecuteQuery();
    
                    if (clientContext.HasPendingRequest)
                        clientContext.ExecuteQuery();
    
                    foreach (ClientOM.File file in files)
                    {
                        FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                        clientContext.ExecuteQuery();
    
                        var filePath = tempLocation + file.Name;
                        using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                        {
                            fileInfo.Stream.CopyTo(fileStream);
                        }
                    }
    
                    return "";
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
    
        }
    }
    

    Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.


    using MvcApplication.Models.Home;
    using System;
    using System.Web.Mvc;
    
    namespace MvcApplication.Controllers
    {
        public class SharepointController : MvcBoostraBaseController
        {
            [HttpPost]
            public ActionResult Upload(FormCollection form)
            {
                try
                {
                    SharepointModel sharepointModel = new SharepointModel();
                    return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return ThrowJSONError(ex);
                }
            }
    
            public ActionResult Download(string ServerUrl, string RelativeUrl)
            {
                try
                {
                    SharepointModel sharepointModel = new SharepointModel();
                    return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    return ThrowJSONError(ex);
                }
            }
        }
    }
    

    If you need the source code of this project you can request it to israelz11@hotmail.com

    0 讨论(0)
  • 2020-11-30 21:08

    Though this is an old post and have many answers, but here I have my version of code to upload the file to sharepoint 2013 using CSOM(c#)

    I hope if you are working with downloading and uploading files then you know how to create Clientcontext object and Web object

    /* Assuming you have created ClientContext object and Web object*/
    string listTitle = "List title where you want your file to upload";
    string filePath = "your file physical path";
    List oList = web.Lists.GetByTitle(listTitle);
    clientContext.Load(oList.RootFolder);//to load the folder where you will upload the file
    FileCreationInformation fileInfo = new FileCreationInformation();
    
    fileInfo.Overwrite = true;
    fileInfo.Content = System.IO.File.ReadAllBytes(filePath);
    fileInfo.Url = fileName;
    
    File fileToUpload = fileCollection.Add(fileInfo);
    clientContext.ExecuteQuery();
    
    fileToUpload.CheckIn("your checkin comment", CheckinType.MajorCheckIn);
    if (oList.EnableMinorVersions)
    {
        fileToUpload.Publish("your publish comment");
        clientContext.ExecuteQuery();
    }
    if (oList.EnableModeration)
    {
         fileToUpload.Approve("your approve comment"); 
    }
    clientContext.ExecuteQuery();
    

    And here is the code for download

    List oList = web.Lists.GetByTitle("ListNameWhereFileExist");
    clientContext.Load(oList);
    clientContext.Load(oList.RootFolder);
    clientContext.Load(oList.RootFolder.Files);
    clientContext.ExecuteQuery();
    FileCollection fileCollection = oList.RootFolder.Files;
    File SP_file = fileCollection.GetByUrl("fileNameToDownloadWithExtension");
    clientContext.Load(SP_file);
    clientContext.ExecuteQuery();                
    var Local_stream = System.IO.File.Open("c:/testing/" + SP_file.Name, System.IO.FileMode.CreateNew);
    var fileInformation = File.OpenBinaryDirect(clientContext, SP_file.ServerRelativeUrl);
    var Sp_Stream = fileInformation.Stream;
    Sp_Stream.CopyTo(Local_stream);
    

    Still there are different ways I believe that can be used to upload and download.

    0 讨论(0)
提交回复
热议问题