Wednesday, May 04, 2011

Downloading the SharePoint Document

Recently,a strange scenario in SharePoint 2010 development I faced.
I created a Visual WebPart with sandbox solution based to let user download the files from the SharePoint Document Library.
Labour the lines of code to get reference of the SPFile from the current web context.
Reading and Writing the file contents into streams to let user to download the file as soon as they clicked it on the "Download" link.It will prompts the "File Download Dialog box".
I deployed it on the sharepoint development environment it just works fine.
Later,I came to know that webpart is not allowing the end user to download.
Again I checked the same webpart performance and put optimised looping and disposing the objects verily stated manner.
Its works fine as I expected.But When I deployed it on SharePoint Server,I faced the same problem when user accessing the page.
When end user clicks the link "Download",Browser redirect to "Forbidden page".

Finally I have concluded the user is only "Reader" permission group.

Simply added RunWithElevatedPrivileges
Its works fine for all user group permission.
protected void Button1_Click(object sender, EventArgs e)
protected void FileAction()
SPWeb site = SPControl.GetContextWeb(Context);
SPFile spFile = site.GetFile(site.Url + "/DocLibrary/" + "1.txt");
// Above line for clarity purpose hard coded.You can read the file name from the //library.My requirement there was only one file.
FileStream fs = new FileStream("C:\\Windows\\Temp\\tempContents.txt", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);

using (FileStream sm = File.Open("C:\\Windows\\Temp\\tempContents.txt", FileMode.Open))
using (StreamReader sr = new StreamReader(sm))
Response.AppendHeader("Content-Disposition", "attachment; filename =" + spFile.Name);
Response.ContentType = "text/plain";
using (StreamWriter sw = new StreamWriter(Response.OutputStream))