使用Microsoft.SharePoint.Client从OneDrive下载文件 [英] download file from OneDrive using Microsoft.SharePoint.Client
问题描述
我有一个winforms应用程序,我需要从Sharepoint OneDrive目录下载文件.目前,根据下面的代码,我可以读取文件Title,但是找不到任何可以帮助我使用 Microsoft.SharePoint.Client 下载代码的内容.
I have a winforms application and I need to download files from a Sharepoint OneDrive directory. Currently, given my code below, I am able to read the file Title, but I can't find anything to help me with downloading the code using Microsoft.SharePoint.Client .
string username = "appuser@abcuseraccount.com";
String pwd = "x!@ex";
ClientContext context = new ClientContext("https://abcuser.sharepoint.com/Main/financial/");
SecureString password = new SecureString();
foreach (char c in pwd.ToCharArray())
{
password.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, password);
context.ExecuteQuery();
List docs = context.Web.Lists.GetByTitle("Financial Notes");
Web site = context.Web;
context.Load(site);
context.ExecuteQuery();
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
ListItemCollection items = docs.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach (ListItem listItem in items)
{
MessageBox.Show(listItem["Title"].ToString());
}
如何将文件下载到本地驱动器(不使用LiveAccount身份验证)?
How can I download the files to my local drive (without using LiveAccount auth)?
推荐答案
Use File.OpenBinaryDirect method to download the specified file from a SharePoint site.
下面的示例演示如何通过提供其项目ID从库中下载文件.
The following example demonstrates how to download file from a Library by providing its item Id.
示例
/// <summary>
/// Download file from a Library
/// </summary>
/// <param name="context">CSOM context</param>
/// <param name="listTitle">List Title</param>
/// <param name="listItemId">List Item Id</param>
/// <param name="downloadPath">Download Path</param>
private static void DownloadFile(ClientContext context, string listTitle, int listItemId, string downloadPath)
{
var list = context.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
context.Load(listItem, i => i.File);
context.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);
var fileName = Path.Combine(downloadPath, listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
这篇关于使用Microsoft.SharePoint.Client从OneDrive下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!