.ashx File Downloader - Auto-Detect MIME Type
<p>I'm throwing together a simple file upload/download component for the navigation menu on our intranet site to give it some really basic document management functionality. It's nothing you probably haven't seen a dozen times before, but the downloader code is included below for reference. This is ASP.NET 3.5 on IIS 7.5</p>

<p>The big question is how can I have the MIME type automatically set using the IIS MIME type map for the site? I'd like to have the handler do its work getting the file content and filename from the database, then tell IIS, "Here, you figure out the MIME type, since you're so good at it."</p>

<pre><code>public void ProcessRequest(HttpContext context) {
    int id = Int32.Parse(context.Request.QueryString["id"]);
    string AttachmentName = null;
    byte[] Attachment = null;
    using (SqlConnection dbconn = new SqlConnection(WebConfigurationManager.ConnectionStrings["NavMenu"].ConnectionString)) {
        dbconn.Open();
        using (SqlCommand sql = new SqlCommand("NavMenu_GetFile", dbconn)) {
            sql.CommandType = CommandType.StoredProcedure;
            sql.Parameters.AddWithValue("@id", id);
            using (SqlDataReader reader = sql.ExecuteReader()) {
                if (reader.Read()) {
                    AttachmentName = reader["AttachmentName"] as string;
                    Attachment = (byte[])reader["Attachment"];
                } else {
                    return;
                }
            }
        }
        dbconn.Close();
    }

    context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", AttachmentName));
    context.Response.BinaryWrite(Attachment);
}
</code></pre>
