开发者

Remote file Download via ASP.NET corrupted file

I am using the code below which I have found on one of the forums to download a file in remote server. it seems it is working. However, the downloaded file is corrupted and I cannot unzip.

Do you have any idea why it is so? or if my approach is wrong, could you suggest me a better way please?

     protected void Page_Load(object sender, EventArgs e)
    {

        string url = "http://server/scripts/isynch.dll?panel=AttachmentDownload&NoteSystem=SyncNotes&NoteType=Ticket&NoteId=1&Field=supp&File=DisplayList%2etxt";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Credentials = new NetworkCredential("user", "pass");
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();


        ////Initialize the output stream
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposi开发者_StackOverflow社区tion:", "attachment; filename=" + "DisplayList.txt");
        Response.AppendHeader("Content-Length", resp.ContentLength.ToString());

        ////Populate the output stream
        byte[] ByteBuffer = new byte[resp.ContentLength];
        Stream rs = req.GetResponse().GetResponseStream();

        rs.Read(ByteBuffer, 0, ByteBuffer.Length);
        Response.BinaryWrite(ByteBuffer);
        Response.Flush();

        ///Cleanup
        Response.End();
        rs.Dispose();
    }


  • First of all, use application/octet-stream as it is the standard content type for downloads.
  • new byte[resp.ContentLength + 1] will define a buffer which is one byte larger than content type. I believe this is the reason for corruption. Use new byte[resp.ContentLength].

I actually recommend re-writing it and removing memorystream:

        const int BufferLength = 4096;
        byte[] byteBuffer = new byte[BufferLength];
        Stream rs = req.GetResponse().GetResponseStream();

        int len = 0;
        while ( (len = rs.Read(byteBuffer,0,byteBuffer.Length))>0)
        {
            if (len < BufferLength)
            {
                Response.BinaryWrite(byteBuffer.Take(len).ToArray());
            }
            else
            {
                Response.BinaryWrite(byteBuffer);
            }
            Response.Flush();   


        }


the article on http://support.microsoft.com/default.aspx?scid=kb;en-us;812406 solved my problem. Many thanks to @Aliostad for his effort to help me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜