下载(打开)PDF文件 代码

网上的代码很多,但现在大多数都是Framework 3.5的啦,对于2.0,2.5有的方法不是很兼容,花了半个小时才找到一个合适,现在记录如下:

注意:不适合网络路径,只适合本地文件, 网络路径请参考我另一篇Blog

public void DownloadFile(string strFileNamePath)

    {

        long chunkSize = 102400;

        byte[] buffer = new byte[chunkSize];

        //long dataToRead=0;

        FileStream stream = null;

        try

        {

            FileInfo info = new FileInfo(strFileNamePath);

            Response.Clear();

            stream = new FileStream(strFileNamePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            Response.Clear();

            Response.AddHeader("Content-Length", stream.Length.ToString());

            Response.ContentType = "application/pdf";

            long fileLength = stream.Length;

            int size = 10240;//10K一--分块下载,10K为1块

            byte[] readData = new byte[size];

            if (size > fileLength)

                size = Convert.ToInt32(fileLength);

            long fPos = 0;

            bool isEnd = false;

            while (!isEnd)

            {

                if ((fPos + size) >= fileLength)

                {

                    size = Convert.ToInt32(fileLength - fPos);

                    isEnd = true;

                }

                readData = new byte[size];

                stream.Position = fPos;

                stream.Read(readData, 0, size);

                Response.BinaryWrite(readData);

                Response.OutputStream.Flush();

                fPos += size;

            }

            stream.Close();

            Response.OutputStream.Close();

            Response.End();//非常重要,没有这句的话,页面的HTML代码将会保存到文件中

            Response.Close();

        }

        catch (Exception)

        {

            if (stream != null)

            {

                stream.Close();

                stream = null;

            }

        }



    }

 

 

你可能感兴趣的:(pdf)