tags:

views:

275

answers:

3

In my ASP.NET application,When I try to open PDF file by using the below code, I am getting an error

CODE USED TO SHOW PDF FILE

FileStream MyFileStream = new FileStream(filePath, FileMode.Open);
long FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize + 1];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename="+filePath);
Response.BinaryWrite(Buffer);

ERROR I AMN GETTING

"There was an error opening this document.The file is damaged and could not open"

A: 

You must flush the response otherwise it gets partially transmitted.

Response.Flush();
Otávio Décio
A: 

In addition to ocedcio's reply, you need to be aware that Stream.Read() does not necessarily read all of the bytes requested. You should examine the return value from Stream.Read() and continue reading if less bytes are read than requested.

See this question & answer for the details: Creating a byte array from a stream

Kevin Pullin
+1  A: 

Sounds like your using an aspx file to output the pdf. Have you considered using an ashx file which is an HttpHandler? It bypasses all the typical aspx overhead stuff and is more efficient for just serving up raw data.

Here is an example of the ashx using your code:

<% WebHandler Language="c#" class="ViewPDF" %>
public class ViewPDF : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        FileStream MyFileStream = new FileStream(filePath, FileMode.Open);
        long FileSize = MyFileStream.Length;
        byte[] Buffer = new byte[(int)FileSize + 1];
        MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
        MyFileStream.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename="+filePath);
        Response.BinaryWrite(Buffer);
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

If you still want to use the aspx page. Make sure you are doing the following:

// At the beginning before you do any response stuff do:
Response.Clear();

// When you are done all your response stuff do:
Response.End();

That should solve your problem.

Kelsey