How to Programatically Download files from sharepoint document library

Rushikesh picture Rushikesh · Jul 7, 2011 · Viewed 9.8k times · Source

On button click event or on Link button click, I want to download document from sharepoint document library and save it to the user's local disk.

Plz help me on this,If you have any code sample then please share

Answer

Andrew Peacock picture Andrew Peacock · Jul 7, 2011

The problem with outputting a direct link to the file, is that for some content types it may just open in the browser window. If that is not the desired outcome, and you want to force the save file dialog, you'll need to write an ASP/PHP page that you could pass a filename to via the querystring. This page could then read the file and set some headers on the response to indicate that the content-disposition is and attachment.

For ASP.net, if you create a simple aspx page called download.aspx, add the following code into it, then put this file on a server somewhere you can download files by calling this page like this:

http://yourserveraddress/download.aspx?path=http://yoursharepointserver/pathtodoclibrary/file.ext

protected void Page_Load(object sender, EventArgs e)
    {
        string path = "";
        string fileName = "";

        path = Request.QueryString["path"];
        if (path != null && path.Length > 0)
        {
            int lastIndex = path.LastIndexOf("/");
            fileName = path.Substring(lastIndex + 1, (path.Length - lastIndex - 1));

            byte[] data;
            data = GetDataFromURL(path);

            Response.Clear();
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.BinaryWrite(data);
            Response.Flush();
        }
    }


    protected byte[] GetDataFromURL(string url)
    {
        WebRequest request = WebRequest.Create(url);
        byte[] result;
        byte[] buffer = new byte[4096];

        //uncomment this line if you need to be authenticated to get to the files on SP
        //request.Credentials = new NetworkCredential("username", "password", "domain");

        using (WebResponse response = request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = responseStream.Read(buffer, 0, buffer.Length);
                        ms.Write(buffer, 0, count);
                    } while (count != 0);
                    result = ms.ToArray();
                }
            }
        }
        return result;
    }