SharePoint file download programmatically

In SharePoint, the file in document library can be downloaded using c# code . In the code below, provide the “ID” of the item and the document library name to download the file. User can download all types of file and will be prompted to save the file.

public static void fileDownload(int DocID, string docLibrary)
{
try
{
SPDocumentLibrary _docLib =     SPContext.Current.Site.RootWeb.Lists.TryGetList(docLibrary) as SPDocumentLibrary;
if (_docLib != null)
{
SPListItem _item = _docLib.GetItemById(DocID);
if (_item != null)
{
SPFile _file = _item.File;
if (_file != null)
{
downloadFiles(_file);
}
}
}
}
catch (Exception ex)
{

}

}

public static void downloadFiles(SPFile _file)
{
try
{
string _filename = _file.Name;
_filename = Regex.Replace(_filename, "[\u2013\u2014]", "-");
string strContentType = "application/octet-stream";
byte[] obj = (byte[])_file.OpenBinary();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + _filename);
HttpContext.Current.Response.ContentType = strContentType;</h6>


    //Check that the client is connected and has not closed the connection after the request
if (HttpContext.Current.Response.IsClientConnected)
{
HttpContext.Current.Response.BinaryWrite(obj);
}
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s