gpt4 book ai didi

asp.net - 通过 ASP.NET 远程文件下载损坏的文件

转载 作者:行者123 更新时间:2023-12-04 06:30:21 25 4
gpt4 key购买 nike

我正在使用我在其中一个论坛上找到的以下代码在远程服务器中下载文件。看来它正在工作。但是,下载的文件已损坏,无法解压缩。

你知道为什么会这样吗?或者如果我的方法是错误的,你能给我建议一个更好的方法吗?

     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-Disposition:", "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();
}

最佳答案

  • 首先,使用application/octet-stream因为它是下载的标准内容类型。
  • new byte[resp.ContentLength + 1]将定义一个比内容类型大一个字节的缓冲区。我相信这就是腐败的原因。使用 new byte[resp.ContentLength] .

  • 我实际上建议重写它并删除内存流:
            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();


    }

    关于asp.net - 通过 ASP.NET 远程文件下载损坏的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5498931/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com