I need to download files from a list from SPO using console app. Since the users have MFA enabled, I am using clientid, clientsecret.
I am able to read the metadata but when I am trying to download a file, it throws 401 unauthorized exception.
I cannot pass the context current credentials as the windows domain and the SharePoint domain are different.
So, is there something missing in the code or do I have to go with MFA authentication to download the file.
Here is the c# code:
using (var cc = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(siteCollectionUrl,ClientId,clientSecret))
{
Web oWebsite = cc.Web;
List list = cc.Web.Lists.GetByTitle("Shared Documents");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View Scope='RecursiveAll'>" +
"<Query>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='FSObjType' />" +
"<Value Type='Integer'>0</Value>" +
"</Eq>" +
"</Where>" +
"</Query>" +
"</View>";//"<View><RowLimit>10000</RowLimit></View>";
ListItemCollection colllist = list.GetItems(camlQuery);
cc.Load(colllist);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
foreach (ListItem oListItem in colllist)
{
DownloadAFile(oListItem, @"C:\Downloads");
}
};
private static void DownloadAFile(Microsoft.SharePoint.Client.ListItem item, string targetPath)
{
var ctx = (ClientContext)item.Context;
var fileRef = (string)item["FileRef"];
var fileName = System.IO.Path.GetFileName(fileRef);
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var filePath = System.IO.Path.Combine(targetPath, fileName);
using (var fileStream = System.IO.File.Create(filePath))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
According to my research and testing, you can use the following code to connect SharePoint with MFA Enabled via CSOM:
And you can using the following code to download file:
More information for reference: Using CSOM To Connect To A SharePoint Site With Multi Factor Authentication Enabled
Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.