Monday, 17 October 2011

Open documents like word, excel in asp.net

I was looking at ways to open word docs or excel docs in asp.net. Most of the solutions i found were related to using the Response object. Specifically using Response.Transmit.
Problem with Response.Transmit is that it does not work if your control is within UpdatePanel. Hence use the code below to open documents if your control is within updatepanel

string filePath = e.CommandArgument.ToString();
FileInfo fileInfo = new FileInfo(Server.MapPath(filePath));
string contentType = string.Empty;

if (fileInfo.Exists)
{
switch (fileInfo.Extension.ToLower())
{
case ".dwf":
contentType = "Application/x-dwf";
break;
case ".pdf":
contentType = "Application/pdf";
break;
case ".doc":
contentType = "Application/vnd.ms-word";
break;
case ".docx":
contentType = "Application/vnd.ms-word";
break;
case ".ppt":
contentType = "Application/vnd.ms-powerpoint";
break;
case ".pps":
contentType = "Application/vnd.ms-powerpoint";
break;
case ".xls":
contentType = "Application/vnd.ms-excel";
break;
case ".txt":
contentType = "Application/octet-stream";
break;
case ".jpg":
contentType = "image/jpeg";
break;
default:
break;
}
}
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.Redirect(filePath, true);

No comments:

Post a Comment