A
AAaron123
If I want to download and display a file on the browser I use the following
code.
Works OK but I wonder if there is a better way to check if the browser can
display a file.
And also, The error message get added to the anchor that is in the aspx file
and they are both displayed as desired, but the image displays without the
anchor showing so the user can not navigate off the page.
Thanks for any help on either question
private void ViewFile(FileInfo file)
{
Response.Clear();
Response.AppendHeader("Content-Disposition", "filename=" + file.Name);
String TypeOfContent = GetContentTypeFromFileExt(file.Extension);
Response.ContentType = TypeOfContent;
if (TypeOfContent.StartsWith("text/") | TypeOfContent.StartsWith("image/"))
{
//Only send if it can be displayed
Response.WriteFile(file.FullName);
}
else
{
Response.Clear();
Response.Write("Can display only text and image files");
}
}
private static string GetContentTypeFromFileExt(string fileExtension)
{
//Retrieve content-type from the system registry given a file extension
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(fileExtension);
try
{
return regKey.GetValue("Content Type",
"application/octet-stream").ToString();
}
catch (Exception)
{
return "application/octet-stream";
}
}
code.
Works OK but I wonder if there is a better way to check if the browser can
display a file.
And also, The error message get added to the anchor that is in the aspx file
and they are both displayed as desired, but the image displays without the
anchor showing so the user can not navigate off the page.
Thanks for any help on either question
private void ViewFile(FileInfo file)
{
Response.Clear();
Response.AppendHeader("Content-Disposition", "filename=" + file.Name);
String TypeOfContent = GetContentTypeFromFileExt(file.Extension);
Response.ContentType = TypeOfContent;
if (TypeOfContent.StartsWith("text/") | TypeOfContent.StartsWith("image/"))
{
//Only send if it can be displayed
Response.WriteFile(file.FullName);
}
else
{
Response.Clear();
Response.Write("Can display only text and image files");
}
}
private static string GetContentTypeFromFileExt(string fileExtension)
{
//Retrieve content-type from the system registry given a file extension
RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(fileExtension);
try
{
return regKey.GetValue("Content Type",
"application/octet-stream").ToString();
}
catch (Exception)
{
return "application/octet-stream";
}
}