Question

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 "Title" of the file, but I can't find anything to help me download the file 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());
}

How can I download the files to my local drive (without using LiveAccount auth)?

Was it helpful?

Solution

Use File.OpenBinaryDirect method to downloads the specified file from a SharePoint site.

The following example demonstrates how to download file from a Library by providing its item Id.

Example

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

Example 2

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); 
    context.ExecuteQuery();

    var fileRef = (string)listItem["FileRef"];
    var fileLeafRef = (string)listItem["FileLeafRef"];
    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileRef);
    var fileDownloadPath = Path.Combine(downloadPath, fileLeafRef);
    using (var fileStream = System.IO.File.Create(fileDownloadPath))
    {
         fileInfo.Stream.CopyTo(fileStream);
    }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top