I need to download a couple of files from a client's Sharepoint. Here is my code:

using Microsoft.SharePoint.Client;

var username = "username";
var password = "pass";

var url = "https://myclient.sharepoint.com/";
var fileurl = "https://myclient.sharepoint.com/teams/folder1/folder%20x/somefile.docx";
using (ClientContext context = new ClientContext(url))
    SecureString passWord = new SecureString();
    foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
    context.Credentials = new SharePointOnlineCredentials(username, passWord);

    Uri filename = new Uri(fileurl);
    string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
    string serverrelative = filename.AbsolutePath;

    Microsoft.SharePoint.Client.File file = context.Web.GetFileByServerRelativeUrl(serverrelative);
    ClientResult<Stream> streamResult = file.OpenBinaryStream();
    var file2 = streamResult.Value;

At first I was getting access denied. We tried logging in through UI and got access denied also. After emailing the client, they told us they gave us permissions. Now we can download the file from UI, but are still getting access denied through this code.

Are there separate permissions between UI/end points? Could the %20 in the space be causing the problem? Is there anything else that could be wrong?

Sorry I am not that familiar with Sharepoint.

  • is it SPOnline or SP on prem? Oct 10, 2018 at 14:37
  • Its the online version (I believe its part of Office365)
    – ColdAir
    Oct 10, 2018 at 14:47

1 Answer 1


Problem was that I was not connecting to the right url (new ClientContext(url))

I was connecting to: https://myclient.sharepoint.com/

I should have been connecting to: https://myclient.sharepoint.com/teams/folder1/

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.