通过ASP.Net网站下载文件

时间:2012-07-11 13:50:54

标签: c# asp.net download

我正在向我的网站用户推送PEM文件以供下载。这是代码:

try
{
    FileStream sourceFile = null;

    Response.ContentType = "application/text";
    Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(RequestFilePath));
    sourceFile = new FileStream(RequestFilePath, FileMode.Open);
    long FileSize = sourceFile.Length;
    byte[] getContent = new byte[(int)FileSize];
    sourceFile.Read(getContent, 0, (int)sourceFile.Length);
    sourceFile.Close();
    Response.BinaryWrite(getContent);
}
catch (Exception exp)
{
    throw new Exception("File save error! Message:<br />" + exp.Message, exp);
}

问题是,下载的文件中应包含的内容+整个网页的HTML副本。

这里发生了什么?

3 个答案:

答案 0 :(得分:5)

放置以下内容......

Response.Clear();

之前...

Response.ContentType = "application/text";

<强>更新

正如@Amiram在他的评论中所说的那样(无论如何我还要补充自己)......

在...

Response.BinaryWrite(getContent);

添加...

Response.End();

答案 1 :(得分:3)

添加以下行:

Response.ClearContent();
Response.ContentType = "application/text";
...

答案 2 :(得分:0)

我同意@Amiram Korach's solution 这是在Response.ClearContent();

之前添加Response.ContentType...

但按照your comment

  

整个页面仍然写完

@Amiram Korach replied最后添加Response.End() 但它抛出了System.Threading.ThreadAbortException

因此,我建议您添加其他catch以捕获System.Threading.ThreadAbortException,并且不要在Response.Write中添加错误消息,否则它也会添加到您的文本文件中:

try
{
    FileStream sourceFile = null;
    Response.ClearContent(); // <<<---- Add this before `ContentType`.
    Response.ContentType = "application/text";
    .
    .
    Response.BinaryWrite(getContent);
    Response.End(); // <<<---- Add this at the end.
}
catch (System.Threading.ThreadAbortException) //<<-- Add this catch.
{
    //Don't add anything here.
    //because if you write here in Response.Write,
    //that text also will be added to your text file.
}
catch (Exception exp)
{
    throw new Exception("File save error! Message:<br />" + exp.Message, exp);
}

这将解决您的问题。