0

I'm writing C# code to download files from a SharePoint Online site. Manually, I am able to access the siteUrl, navigate to the folderPath, and read/write on the files in there. However when I run my code below, I get this error:

Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: 'Access denied. You do not have permission to perform this action or access this resource.'.

I've also tried going the OpenBinaryDirect path, but I kept getting 404 Not Found errors even though my urls are correct.

internal static void DownloadFilesFromSharePoint(string siteUrl, string folderPath, string tempLocation)
{
    string username = "my.username@company.com";
    string passwordFromForm = "password.from.form";

    var securedPassword = new SecureString();
    foreach (var c in passwordFromForm.ToCharArray()) securedPassword.AppendChar(c);
    ClientContext ctx = new ClientContext(siteUrl);
    ctx.Credentials = new SharePointOnlineCredentials(username, securedPassword);

    FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(folderPath).Files;

    ctx.Load(files);
    ctx.ExecuteQuery(); //Error here    

    foreach (Microsoft.SharePoint.Client.File file in files)
    {
        FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
        ctx.ExecuteQuery();

        var filePath = tempLocation + file.Name;
        using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
        {
            fileInfo.Stream.CopyTo(fileStream);
        }
    }
}
  • do you have Multi factor authentication enabled for your account? – Abdul Hameed Mar 22 '18 at 14:45
  • Since the error is thrown after this part: FileCollection files = ctx.Web.GetFolderByServerRelativeUrl(folderPath).Files;, it has nothing to do with how you open/read each file, and thus OpenBinaryDirect won't solve the problem. – Abbas Mar 22 '18 at 14:51
  • @AbdulHameed Nope, no multi-factor authentication. – Chris Mar 23 '18 at 2:56
0

I found that the problem was that while my account had direct access to the specific folder in folderPath, it did not have access to the root folder of Shared Documents (this list is empty if I browse to it manually). It seems that GetFolderByServerRelativeUrl cannot access the folder directly and needs to traverse the path from the root to access it. After being granted access, the code now works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.