Kendo Kendo - 10 months ago 52
SQL Question

file extensions lost between browsers in c# application

I have a technical question for some of you.

Basically i have been testing my application primarily in firefox, I have a download feature in the application where the user can download a file from SQL server database. The problem is that when i download the file in Internet explorer every file will lose its extension apart from the Microsoft files e.g. word, access etc. There are no problems in firefox apart from bitmaps...

here is my code and thank you

//Download attachment file
protected void AttachmentDLBut_Click(object sender, EventArgs e)
//set the ID for the selected row
var ID = Request.QueryString["Id"];
using (SqlConnection conn = new SqlConnection("******"))
string sql = "SELECT FileType, Filename, Description FROM NetworkEquipment WHERE NetworkEquipmentID = '" + ID + "'";

using (SqlCommand cmd = new SqlCommand(sql, conn))
//cmd.Parameters.AddWithValue("@ID", AttachmentDDL.SelectedItem.Value);

SqlDataReader dr = cmd.ExecuteReader();

//if there is an attachment... download it
if (dr.Read())
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["Filename"].ToString());

catch (SqlException sqlex) { MessageBox.Show("Sorry, an unexpected error has occurred while downloading this file. Error: " + sqlex); }
catch (Exception ex) { MessageBox.Show("Sorry, an unexpected error has occurred while downloading this file. Error: " + ex); }

//else nothing happens

Ben Ben
Answer Source

Use F12 developer tools or FireBug or similar to see what is actually sent by the server. In this case it will be something like:

Content-Disposition: attachment;filename="filename.ext

The server may also send this or something similar by default:

Content-Type: text/html

Firstly, you need to close the quotes after filename. A space after the semicolon is also recommended. You also need to clean up the filename to make sure it doesn't contain confusing or illegal characters. At the very least you need to strip double quotes or quote them.

Secondly you need to add a Content-Type header. The cheat is to set

Content-Type: application/octet-stream 

which will result in the browser guessing based on the file extension.