Unable to download list file with client id and secret key c#

Copper Contributor

Hi,

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

 Thanks.

0 Replies