使用Microsoft.SharePoint.Client从OneDrive下载文件

本文关键字:OneDrive 下载 文件 Client Microsoft SharePoint 使用 | 更新日期: 2023-09-27 18:17:36

我有一个winforms应用程序,我需要从Sharepoint OneDrive目录下载文件。目前,给出我下面的代码,我能够读取文件标题,但我找不到任何东西来帮助我使用Microsoft.SharePoint下载代码。客户

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授权)?

使用Microsoft.SharePoint.Client从OneDrive下载文件

使用文件。OpenBinaryDirect方法,从SharePoint站点下载指定文件。

下面的示例演示如何通过提供项目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);
    }
}