File.OpenBinaryDirect throws error 401/403 in SharePoint 2013 Provider Hosted App (Add-Ins)

I was trying to get a file from a SharePoint document library (host-web) with the .NET Client Object Model (CSOM) in a provider hosted app. I used the OpenBinaryDirect method from the File-class.

Code Snippet
  1. List spList = ctx.Web.Lists.GetByTitle(“Dokumente”);
  2. CamlQuery camlQuery = new CamlQuery {ViewXml = String.Format(@”<View> 
  3.         <Query>
  4.             <Where><Eq><FieldRef Name=’FileLeafRef’ /><Value Type=’File’>{0}</Value></Eq></Where>
  5.         </Query>
  6.         <ViewFields><FieldRef Name=’ID’ /><FieldRef Name=’FileRef’ /><FieldRef Name=’FileLeafRef’ /><FieldRef Name=’FileSizeDisplay’ /><FieldRef Name=’Title’ /></ViewFields>
  7.         </View>”, filename)};
  8. ListItemCollection listItems = spList.GetItems(camlQuery);
  9. ctx.Load(listItems);
  10. ctx.ExecuteQuery();
  11. if (listItems.Count != 1) return null;
  12. var item = listItems.First();
  13. File file = item.File;
  14. ctx.Load(file);
  15. ctx.ExecuteQuery();
  16. FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);

 

But I’m getting a 401 unauthorized error, while the credentials are correct in the ClientContext.

image

After searching, I found this post: http://tech-karma.blogspot.se/2013/05/sharepoint-2013-online-app-403-response.html. It explained that OpenBinaryDirect is unable to evaluate the AppToken and is therefore unable to access SharePoint.

The solution is to use the OpenBinaryStream method of the File class. The result is delivered as a ClientResult. The file access works with:

Code Snippet
  1. //FileInformation fileInfo = File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);       
  2. var clientResultStream = file.OpenBinaryStream();
  3. ctx.ExecuteQuery();
  4. var stream = clientResultStream.Value;
The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

About Thomas Zühlke 3 Articles
Senior Consultant and solution architect for digital transformation and Business solutions in midsize and large companies. SharePoint-fan since SharePoint 2007 and MCPD/MCSD in SharePoint 2010/2013. Now more focued on cloud topics (DevOps, cloud-native-apps, Containers) and especially on Azure.

1 Comment

Leave a Reply

Your email address will not be published.


*