Nov 27 2022 11:49 AM
I’m trying to write a c# app that will download files from sharepoint onedrive using the rest sharepoint API
Does anyone know how this can be done?
Nov 28 2022 01:35 AM
@A-Gon350
Sure... Onedrive is basically just a site collection just for you.
I use the "PnP.Framwork" library for that
This sample downloads all files from the folder "downloadfolder" in your onedrive to your local folder.
It uses username/passwort authentication, but the "Authenticationmanager" xlass supports many other authentication methods
string usernamne = "username";
string password = "password";
string folderPath = "/personal/<User>/downloadfolder";
string siteUrl = "https://<tenant>-my.sharepoint.com/personal/<User>/";
// Authenticationmanager supports many different authentication methods, see documentation
AuthenticationManager auth = new AuthenticationManager(username, password);
ClientContext ctx = auth.GetContext(siteUrl);
var folder=ctx.Web.GetFolderByServerRelativeUrl(folderPath);
ctx.Load(folder);
ctx.Load(folder.Files);
ctx.ExecuteQueryRetry();
foreach(var file in folder.Files)
{
Console.WriteLine(file.Name);
ctx.Load(file);
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.ClientResult<Stream> mstream = file.OpenBinaryStream();
ctx.ExecuteQuery();
var fileName = Path.Combine( Directory.GetCurrentDirectory(),"data", (string)file.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
mstream.Value.CopyTo(fileStream);
}
}
Dec 19 2022 09:48 AM
im getting this error. do you by any chance know why? i cant seem to find any information on it
Dec 19 2022 10:48 PM
@A-Gon350
Mhm.... try to convert the password into a securestring
var securePassword = new SecureString();
foreach (char c in userPassword)
{
securePassword.AppendChar(c);
}
AuthenticationManager auth = new AuthenticationManager(userLogin, securePassword);