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

Submit comment

Allowed HTML tags: <a href="http://google.com">google</a> <strong>bold</strong> <em>emphasized</em> <code>code</code> <blockquote>
quote
</blockquote>

Please fill in the captcha: * Time limit is exhausted. Please reload CAPTCHA.