0

I have a site that allows users to upload a document such as pdf, word, excel etc.

Now in my code, when I want to show the document in a browser, I am checking for the extension and setting the ContentType appropriately.

However, this switch statement just doesn't sound like the best solution.

Is there a way I can set the content type based on the Stream?

griegs
  • 22,624
  • 33
  • 128
  • 205

1 Answers1

0

If you don't want to use switch like statements, use Dictionary to add possible MIME-entries.

Dictionary<string, string> map=new Dictionary<string, string>
{
  {"txt", "text/plain"},                                                
  {"exe", "application/octet-stream"},
  {"bmp", "image/bmp"}
};

and set content type,

Response.ContentType=map[ext];

I've found an interesting stackoverflow thread - Using .NET, how can you find the mime type of a file based on the file signature not the extension

Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • AVD, thanks for this. I guess by your answer then there is no real way to infer the type from either the byte array or the stream? – griegs Sep 26 '11 at 03:09
  • @griegs - Please check the link I've added. – KV Prajapati Sep 26 '11 at 03:10
  • Thanks for that. I can't user Urlmon but based on your solution of a dictionary, I found this handy class. https://github.com/cymen/ApacheMimeTypesToDotNet/blob/master/ApacheMimeTypes.cs – griegs Sep 26 '11 at 03:26