我正在使用我在其中一个论坛上找到的代码来下载远程服务器中的文件。它似乎工作。但是,下载的文件已损坏,我无法解压缩。
你知道为什么会这样吗?或者如果我的方法有误,你能建议我一个更好的方法吗?
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();
}
答案 0 :(得分:2)
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();
}
答案 1 :(得分:1)
关于http://support.microsoft.com/default.aspx?scid=kb;en-us;812406的文章解决了我的问题。非常感谢@Aliostad帮助我的努力。