简体   繁体   中英

Download a file through ASP.Net website

I'm pushing a PEM file towards my website user for download. here is the code:

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);
}

The issue is that the file that is downloaded has the content that should be there + a copy of the whole web page's HTML too.

Whats happening here?

Place the following...

Response.Clear();

Before...

Response.ContentType = "application/text";

Update

As @Amiram says in his comments (and I was about to add myself anyway)...

After...

Response.BinaryWrite(getContent);

Add...

Response.End();

Add this line:

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

I agree with @Amiram Korach's solution .
That is add Response.ClearContent(); before Response.ContentType...

But as per your comment

Still the whole page get written

@Amiram Korach replied to add Response.End() at the end.
But it throws System.Threading.ThreadAbortException .

So I advice you to add additional catch to catch System.Threading.ThreadAbortException and don't put error message in Response.Write otherwise it will also be added to your text file:

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);
}

This will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM