Thursday, May 3, 2012

Open MS Word document in web browser

 

This is one of the common request you will get when you do any file operation in your project. This code can be used to open EXCEL, Power Point, PDF etc.

protected void btnWord_Click(object sender, EventArgs e)
{
    string strWordFile = @"c:/Test.docx";
    FileInfo objDoc = new FileInfo(strWordFile);
    Response.Clear();
    Response.ContentType = "Application/msword";
    Response.AddHeader("content-disposition", "attachment;filename=" + objDoc.Name);
    Response.AddHeader("Content-Length", objDoc.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.TransmitFile(objDoc.FullName); 
    Response.End(); 
}

1 comment:

Krk said...

Could not find file 'F:/Test.doc'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not find file 'F:/Test.doc'.

Source Error:


Line 20: Response.ContentType = "Application/msword";
Line 21: Response.AddHeader("content-disposition", "attachment;filename=" + objDoc.Name);
Line 22: Response.AddHeader("Content-Length", objDoc.Length.ToString());
Line 23: Response.ContentType = "application/octet-stream";
Line 24: Response.TransmitFile(objDoc.FullName);

Source File: d:\SendSMs\Sendsms1\Default2.aspx.cs Line: 22