File Download from SharePoint Document Library in Forms Based Authentication Scenario

I was writing the code for downloading a file from a SharePoint document library using Forms Based Authentication. Every time
file was getting downloaded with 8kb of size when i was opening them they were showing that file is not supported. I opened
one of downloaded files that was actually a word file, in notepad and i found some HTML code was inserting inside that file.
After looking the script i found that it was not actual file rather it was the login page of SharePoint site.. Humnn it means
there was some authentication problem while downloading and site was not authenticate the request for downloading the file
and hence request was redirecting to the login page.
I was using System.Net.WebClient and after some research i came to know that this class wouldn’t work directly in case of
Forms Based Authentication as it can’t persist the authentication credentials throughout the request.
I found that if i use HttpWebRequest, i can download the file but limitation of HttpWebRequest class is it can’t download a larger file.
Well i used the HttpWebRequest without any success.I was providing all proper credentials, method was executing without any exception and producing earlier result. It was driving me crazy. After hours of searching on net i couldn’t find any thing…
Well after reading some interesting things from different articles i decide to write my own class and method. So below is the
code by that i could achieve the expected result.

Step 1st:
Create a custom class inheriting from System.Net.WebClient. This class will take the object of CookieContainer class while
initializing, and it will override GetWebRequest method of System.Net.WebClient to change the default behavior of method
so that it can use of cookies and maintain the authentication credentials while making requests.

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class CustomWebClient : WebClient
{

private CookieContainer _cookies;
public CustomWebClient(CookieContainer cookies)
{
_cookies = cookies;
}

protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = _cookies;
return request;
}
}

Step 2nd:
Write a method to download the requested file. This method will actually call Authentication.asmx web service of SharePoint
site. Then it will take credentials and authenticate the request. After successful authentication it will create authenticated
cookie then we will add this cookie in a CookieContainer object and pass the object while initializing CustomWebClient object.

public void FBACookieAuthentication(string authenticationWSAddress, string userName, string password, string retVal, string docUrl)
{
try {
//retval=Download location on hard drive including document file name e.g. c:\MyFolder\SetUp.doc
//docUrl=Full url of the document needs to be downloaded e.g. http://loclahost/TEST/Error%20Resolution%20STSADM.txt
Authentication spAuthentication = new Authentication();
spAuthentication.Url = authenticationWSAddress;
spAuthentication.CookieContainer = new CookieContainer();
//Try to login to SharePoint site with Form based authentication
LoginResult loginResult = spAuthentication.Login(userName, password);
Cookie cookie = new Cookie();
//If login is successfull
if (loginResult.ErrorCode == LoginErrorCode.NoError) {
//Get the cookie collection from the authenticatin web service
CookieCollection cookies = spAuthentication.CookieContainer.GetCookies(new Uri(spAuthentication.Url));
//Get the specific cookie which contains the security token
cookie = cookies[loginResult.CookieName];
//Initialize the cookie container of the list web service
CookieContainer cc = new CookieContainer();
cc.Add(cookie);
CustomWebClient httpRequest = new CustomWebClient(cc);
httpRequest.DownloadFile(docUrl, retVal);
}

} catch (SoapException ex) {
this.LogMessageToFile(“Exception Occured:” + ex.ToString());
} catch (Exception ex) {
this.LogMessageToFile(“Exception Occured:” + ex.ToString());
}
this.LogMessageToFile(“End FBACookieAuthentication method”);
}

That’s it………. Hope this blog entry will be useful to you……… Happy SharePointing 🙂