-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);
}
Jim
  • 2,974
  • 2
  • 19
  • 29
AlexGH
  • 2,735
  • 5
  • 43
  • 76

2 Answers2

4

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

Community
  • 1
  • 1
Jonathan M
  • 1,891
  • 13
  • 21
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");
Shyju
  • 214,206
  • 104
  • 411
  • 497