AlexGH AlexGH - 1 year ago 88
C# Question

How to know the extension of documents/files?

I need to know the extension of different documents and depending of the extensions take some decisions within my code: for example I can have this FileNames:

commands to save.docx

Old Word.doc



I know that using the
method that comes with Linq I could do something but I'm afraid that using
it will take a
extension even if is a
extension because
is a

I think that a better approach would be maybe a regular expression for this... Any suggestion?

I've done something like this but maybe a
should be a better approach:

if (fileName.Contains(".pdf"))
Response.AddHeader("Content-Type", "application/pdf; Content-Disposition, inline" + fileName);

Answer Source

You may use the MimeMapping.GetMimeMapping method the mime type of the document. With that,you do not really need to get the file extension and write those if condition for all the different types.

var fileName = Path.GetFileName("SomeFileNameWithLongPath.pdf");
string mimeType= MimeMapping.GetMimeMapping(fileName );

If you really want the extension, you can use the Path.GetExtension method

var extension = Path.GetExtension("SomeFileNameWithLongPath.pdf");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download