Forum Discussion
A-Gon350
Nov 27, 2022Copper Contributor
Download files from sharepoint onedrive
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?
SvenSieverding
Nov 28, 2022Bronze Contributor
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);
}
}
- A-Gon350Dec 19, 2022Copper Contributor
im getting this error. do you by any chance know why? i cant seem to find any information on it
- SvenSieverdingDec 20, 2022Bronze Contributor
A-Gon350
Mhm.... try to convert the password into a securestringvar securePassword = new SecureString(); foreach (char c in userPassword) { securePassword.AppendChar(c); } AuthenticationManager auth = new AuthenticationManager(userLogin, securePassword);