Reputation: 517
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 = "[email protected]";
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)?
Upvotes: 1
Views: 2533
Reputation: 59318
Use File.OpenBinaryDirect method to download 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);
}
}
Upvotes: 2