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

2019-10-20 16:06发布

我有一个WinForms应用程序,我需要从SharePoint OneDrive目录下载文件。 目前,鉴于我下面的代码,我能够读取该文件标题,但我无法找到任何东西帮我下载使用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 AUTH)?

Answer 1:

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

下面的例子演示了如何从一个库通过提供其项目编号下载文件。

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


文章来源: download file from OneDrive using Microsoft.SharePoint.Client