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 = "[email protected]";
    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.ExecuteQuery(); //Error here    

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

        var filePath = tempLocation + file.Name;
        using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
  • do you have Multi factor authentication enabled for your account? Commented Mar 22, 2018 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
    Commented Mar 22, 2018 at 14:51
  • @AbdulHameed Nope, no multi-factor authentication.
    – Chris
    Commented Mar 23, 2018 at 2:56

1 Answer 1


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 and acknowledge you have read our privacy policy.

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