I have a page which is supposed to transmit a file 

All the code is surrounded in a try / catch Exception block

I use Response.TransmitFile to actually write the file, and when it fails (Due to permission issue in my case) the response to the client is some automatically generated html which details the error, with one part saying: "An unhandled exception was generated during the execution of the current web request."

Why does it say unhandled exception? 

I caught the error because the headers were changed to text/html instead of the octet stream it would have been set to had the file proceeded successfully. But it seems like the call to TransmitFile writes its own content to the Response and then flushes it, which would really be undesirable! 

What can I do?

```
try
{
    String targetFile = Request.Form["filePath"];
    if (targetFile == null) throw new Exception("No filename provided");
    FileInfo file = new FileInfo(targetFile); 
    if (!file.Exists)
    {
        // file not found error
        throw new Exception("File not found");
    }

        Response.ContentType = "APPLICATION/OCTET-STREAM";
        Response.AppendHeader("Content-Disposition", "Attachment; Filename=\"" + Path.GetFileName(targetFile) + "\"");

        Response.TransmitFile(file.FullName);

} 
catch (Exception e) 
{
    Response.ClearHeaders();
    Response.ClearContent();
    Response.ContentType = "text/html";

    StringBuilder sb = new StringBuilder();
    // I write my own response in sb - I never see this content sent back!!
    Response.Write(sb.ToString());
    Response.Flush();
}

```