Use CSOM ClientContext to fetch documents from users personal OneDrive for Business

Say I want to provide the user a list of their personal files in their OneDrive for Business site – this is how to do it.  Note: this is for OneDrive for Business, not the standard OneDrive – for that see this article.

In essence each users personal files are in their own site collection. So we need to get the web url. You can see what the web url should be by browsing to your own OneDrive in the browser.  In my example Im going to use:

https://isharepoint-my.sharepoint.com/personal/luqman_isharepoint_onmicrosoft_com

So that makes sense but what we actually need is the users own personal url, not mine.  For this we need to get the current user object then fetch their email address.  Replace any periods and @ symbols characters with underscores.  For this we can use the main tenant url as we dont current know what the personal site collection url is:

ClientContext  Context = new ClientContext(https://isharepoint.sharepoint.com);​

Authenticator at = new Authenticator();

at.CookieCachingEnabled = true;

Context.Credentials = at;

web = Context.Web;

Context.Load(web);

currentUser = web.CurrentUser;

Context.Load(currentUser);

Context.ExecuteQuery();

string email = currentUserEmail;

 

The code above has been changed a bit from the actual to make it a bit clearer but you should get the idea of whats going on. Also its for windows phone 8 app, for a sharepoint you wont need to worry about the authentication.

OK, now that we have the email address we need to replace the characters to make it the same as users personal folder url:

email = email.Replace(“.”, “_”).Replace(“@”, “_”);

 

Next we get a ClientContext to the users personal site collection of:

https://isharepoint-my.sharepoint.com/personal/”+email+”/”);

Once we have that we need to access the Documents library. We do this jus the same way we would with any other document library and there are hundreds of articles online showing how to query list and libraries.