Article: Download (Save) VARBINARY Data as File in ASP.Net using C# and VB.Net
Hi
In the download section, only the Firefox browser recognizes the file format, and other browsers such as Google Chrome download the file, but it does not recognize the file type. How to solve this problem?
This is Function For Get ContentType:
private string GetContentType(string fileExtension)
{
if (string.IsNullOrEmpty(fileExtension))
return string.Empty;
string contentType = string.Empty;
switch (fileExtension)
{
case ".htm":
case ".html":
contentType = "text/HTML";
break;
case ".txt":
contentType = "text/plain";
break;
case ".doc":
case ".rtf":
case ".docx":
contentType = "application/msword";
break;
case ".xls":
case ".xlsx":
contentType = "application/x-msexcel";
break;
case ".jpg":
case ".jpeg":
contentType = "image/jpeg";
break;
case ".gif":
contentType = "image/GIF";
break;
case ".pdf":
contentType = "application/pdf";
break;
case ".dwg":
contentType = "application/acad";
break;
}
return contentType;
}
This is My Code For Download File:
Random myrandom = new Random();
int MyValue = myrandom.Next();
string FileName = "tmpFile_" + MyValue.ToString();
string ContentType = string.Empty;
byte[] FileData = null;
ConnectionString = CryptorEngine.Decrypt(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString, true);
SqlConnection ConMain = new SqlConnection();
ConMain.ConnectionString = ConnectionString;
ConMain.Open();
SqlCommand CmdMain = new SqlCommand();
CmdMain.Connection = ConMain;
CmdMain.CommandType = CommandType.StoredProcedure;
CmdMain.CommandText = "SP_ShowSelectFile";
CmdMain.Parameters.AddWithValue("@File_ID", int.Parse(this.lbFileID.Text.Trim()));
SqlDataReader DrData = CmdMain.ExecuteReader();
DrData.Read();
ContentType = DrData["FileExtension"].ToString();
FileData = (byte[])DrData["FileData"];
DrData.Close();
ConMain.Close();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = GetContentType(ContentType);
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.AppendHeader("Content-Lenght", FileData.Length.ToString());
Response.BinaryWrite(FileData);
this.Context.ApplicationInstance.CompleteRequest();