AlexGH AlexGH - 1 month ago 12
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

rel.txt

test.pdf


I know that using the
Contains()
method that comes with Linq I could do something but I'm afraid that using
Contains()
it will take a
.doc
extension even if is a
.docx
extension because
.doc
is a
substring
of
.docx


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
RegEx
should be a better approach:

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

Answer

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");