-1

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);
}
0

2 Answers 2

4

You will find what you seek here, using Path.GetExtension

3
  • 1
    Links are not good naswers, put relevant code to the question. Oct 31, 2016 at 23:12
  • 1
    @mybirthname it shouldn't have been an answer at all, this should have been marked as duplicate, and in general, links to relevant information should be added with a quote, doesn't mean there shouldn't be a link.
    – Dispersia
    Oct 31, 2016 at 23:26
  • 1
    @Dispersia Indeed. Fixed :)
    – Ivan Stoev
    Oct 31, 2016 at 23:44
1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.