web-dev-qa-db-fra.com

Comment télécharger/télécharger des fichiers de/vers SharePoint 2013 à l'aide de CSOM?

Je développe une application cliente (CSOM) Win8 (WinRT, C #, XAML) qui doit télécharger/télécharger des fichiers de/vers SharePoint 2013.

Comment faire le téléchargement/upload?

27
eitan barazani

Télécharger un fichier

Téléchargez un fichier sur un site SharePoint (y compris SharePoint Online) à l'aide de File.SaveBinaryDirect, méthode :

using (var clientContext = new ClientContext(url))
{
     using (var fs = new FileStream(fileName, FileMode.Open))
     {
         var fi = new FileInfo(fileName);
         var list = clientContext.Web.Lists.GetByTitle(listTitle);
         clientContext.Load(list.RootFolder);
         clientContext.ExecuteQuery();
         var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);

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

Télécharger un fichier

Téléchargez le fichier à partir d'un site SharePoint (y compris SharePoint Online) à l'aide de File.OpenBinaryDirect, méthode :

using (var clientContext = new ClientContext(url))
{

     var list = clientContext.Web.Lists.GetByTitle(listTitle);
     var listItem = list.GetItemById(listItemId);
     clientContext.Load(list);
     clientContext.Load(listItem, i => i.File);
     clientContext.ExecuteQuery();

     var fileRef = listItem.File.ServerRelativeUrl;
     var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
     var fileName = Path.Combine(filePath,(string)listItem.File.Name);
     using (var fileStream = System.IO.File.Create(fileName))
     {                  
          fileInfo.Stream.CopyTo(fileStream);
     }
}
50
Vadim Gremyachev

Cet article décrit diverses options pour accéder au contenu SharePoint. Vous avez le choix entre REST et CSOM. J'essaierais de CSOM si possible. Le téléchargement de fichiers est spécifiquement décrit dans l'article this .

Notes globales:

    //First construct client context, the object which will be responsible for
    //communication with SharePoint:
    var context = new ClientContext(@"http://site.absolute.url")

    //then get a hold of the list item you want to download, for example
    var list = context.Web.Lists.GetByTitle("Pipeline");
    var query = CamlQuery.CreateAllItemsQuery(10000);
    var result = list.GetItems(query);

    //note that data has not been loaded yet. In order to load the data
    //you need to tell SharePoint client what you want to download:

    context.Load(result, items=>items.Include(
        item => item["Title"],
        item => item["FileRef"]
    ));

    //now you get the data
    context.ExecuteQuery();

    //here you have list items, but not their content (files). To download file
    //you'll have to do something like this:

    var item = items.First();

    //get the URL of the file you want:
    var fileRef = item["FileRef"];

    //get the file contents:
    FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());

    using (var memory = new MemoryStream())
    {
          byte[] buffer = new byte[1024 * 64];
          int nread = 0;
          while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
          {
              memory.Write(buffer, 0, nread);
          }
          memory.Seek(0, SeekOrigin.Begin);
          // ... here you have the contents of your file in memory, 
          // do whatever you want
    }

Évitez de travailler directement avec le flux, lisez-le d'abord dans la mémoire. Les flux liés au réseau ne prennent pas nécessairement en charge les opérations de flux, sans parler des performances. Ainsi, si vous lisez une image de ce flux ou analysez un document, vous pouvez vous retrouver avec un comportement inattendu.

Sur une note de côté, j'ai une question connexe concernant la performance de ce code ci-dessus, car vous prenez une pénalité avec chaque demande de fichier. Voir ici . Et oui, vous avez besoin de 4,5 profils .NET complets pour cela.

26
Borv

File.OpenBinaryDirect peut provoquer une exception lorsque vous utilisez le jeton d'accès Oauth Expliqué dans Cet article

Le code doit être écrit comme ci-dessous pour éviter les exceptions

 Uri filename = new Uri(filepath);
        string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, 
         "");
        string serverrelative = filename.AbsolutePath;

        Microsoft.SharePoint.Client.File file = 
        this.ClientContext.Web.GetFileByServerRelativeUrl(serverrelative);
        this.ClientContext.Load(file);
        ClientResult<Stream> streamResult = file.OpenBinaryStream();
        this.ClientContext.ExecuteQuery();
        return streamResult.Value;
5
Ram chittala
Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
    Try
        destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
        Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
        Dim down As Stream = System.IO.File.Create(destinationPath)
        Dim a As Integer = fi.Stream.ReadByte()
        While a <> -1
            down.WriteByte(CType(a, Byte))
            a = fi.Stream.ReadByte()
        End While
    Catch ex As Exception
        ToLog(Type.ERROR, ex.Message)
    End Try
End Sub
1
Angel

Un peu tardivement ce commentaire mais je laisserai ici mes résultats travailler avec la bibliothèque de SharePoin Online et il est très facile à utiliser et à implémenter dans votre projet, allez simplement chez l’administrateur NuGet de .Net et ajoutez projet.

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

L'extrait de code suivant vous aidera à connecter vos informations d'identification à votre site SharePoint. Vous pouvez également lire et télécharger des fichiers à partir d'un site et d'un dossier spécifiques.

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 = "[email protected]";
        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);
            }
        }

    }
}

Ensuite, invoquer les fonctions à partir du contrôleur dans ce cas, MVC ASP.NET est effectué de la manière suivante .


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

Si vous avez besoin du code source de ce projet, vous pouvez le demander à [email protected]

1
Israel' De la Cruz

Bien que ce soit un ancien message et que je dispose de nombreuses réponses, mais ici, j’ai ma version du code sur upload le fichier sur sharepoint 2013 en utilisant CSOM (c #)

J'espère que si vous travaillez avec le téléchargement et le téléchargement de fichiers, vous savez comment créer des objets Clientcontext et Web

/* 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();

Et voici le code à télécharger

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

Il existe néanmoins différentes manières, selon moi, de télécharger et de télécharger.

0

Je suggère de lire une documentation Microsoft sur ce que vous pouvez faire avec CSOM. Cela pourrait être un exemple de ce que vous recherchez, mais il existe une énorme API documentée dans msdn.

// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.Items.GetById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery(); 

De: http://msdn.Microsoft.com/en-us/library/fp179912.aspx

0
Dan Teesdale

Une simple suggestion pour le codage de fichiers en ligne et sur site SharePoint 2013 est la nomenclature UTF-8 . Assurez-vous que votre fichier est une nomenclature UTF-8, faute de quoi le code HTML et les scripts téléchargés risquent de ne pas être restitués correctement dans le navigateur.

0
karayakar