Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
808 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Upload a file

Upload a file to a SharePoint site (including SharePoint Online) using File.SaveBinaryDirect Method:

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

Download file

Download file from a SharePoint site (including SharePoint Online) using File.OpenBinaryDirect Method:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...