Code to download files from a SharePoint 2010 site using Claims Based Authentication

Trying to download some images from a SharePoint 2010 Image Library using code I was getting HPPT Status 401 – Unauthorized.

First thing I check was the user name and password in a browser window. It worked just fine.

This code used to work for SharePoint 2007 but then I recalled the site uses Claims Based Authentication and it needs a little change in order to authenticate a user on 2010.

Checking the definitions for Windows Authentication requests on SharePoint 2010 I saw we need to specify the X-FORMS_BASED_AUTH_ACCEPTED and the user agent HTTP headers .

Follow a code snippet:

string url = @"File URL";
string userName = "account";
string password = "password";
string domain = "domain";


NetworkCredential credential = new NetworkCredential(userName, password, domain);
WebClient client = new WebClient();
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
client.Credentials = credential;
byte[] data = client.DownloadData(url);


After this code change it worked just fine.

See you,

Amadeu.