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?

Télécharger un fichier

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

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 = Ssortingng.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 la méthode File.OpenBinaryDirect :

 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,(ssortingng)listItem.File.Name); using (var fileStream = System.IO.File.Create(fileName)) { fileInfo.Stream.CopyTo(fileStream); } } 

Cet article décrit différentes 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 cet article.

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.ToSsortingng()); 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 stream, lisez-le d’abord dans la mémoire. Les stream liés au réseau ne prennent pas nécessairement en charge les opérations de stream, sans parler des performances. Ainsi, si vous lisez une image de ce stream ou parsingz 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.

File.OpenBinaryDirect peut provoquer une exception lorsque vous utilisez Oauth accestoken Expliqué dans cet article

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

  Uri filename = new Uri(filepath); ssortingng server = filename.AbsoluteUri.Replace(filename.AbsolutePath, ""); ssortingng serverrelative = filename.AbsolutePath; Microsoft.SharePoint.Client.File file = this.ClientContext.Web.GetFileByServerRelativeUrl(serverrelative); this.ClientContext.Load(file); ClientResult streamResult = file.OpenBinaryStream(); this.ClientContext.ExecuteQuery(); return streamResult.Value; 
 Private Sub DownloadFile(relativeUrl As Ssortingng, destinationPath As Ssortingng, name As Ssortingng) 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 

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

Juste une suggestion Le codage de fichiers en ligne et sur site SharePoint 2013 est la nomenclature UTF-8. Assurez-vous que votre fichier est au format BOM UTF-8, sinon le HTML et les scripts que vous avez téléchargés risquent de ne pas être restitués correctement dans le navigateur.