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

后端 未结 8 2157
佛祖请我去吃肉
佛祖请我去吃肉 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: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.

提交回复
热议问题