Regular expression to check the type of contents of the -doc file or not?

When I use file upload, I use to check the contents of the content file with regular expressions ... For ex

private bool IsImage(HttpPostedFile file) { if (file != null && Regex.IsMatch(file.ContentType, "image/\\S+") && file.ContentLength > 0) { return true; } return false; } 

This returns my file, this image or not ... How to check this document (.doc / .docx) or not to use C # ...

+4
source share
5 answers

For example, using Axarydax's answer: (so check docx mime)

 List<String> wordMimeTypes = new List<String>(); wordMimeTypes.Add("application/msword"); wordMimeTypes.Add("application/doc"); wordMimeTypes.Add("appl/text"); wordMimeTypes.Add("application/vnd.msword"); wordMimeTypes.Add("application/vnd.ms-word"); wordMimeTypes.Add("application/winword"); wordMimeTypes.Add("application/word"); wordMimeTypes.Add("application/x-msw6"); wordMimeTypes.Add("application/x-msword"); //etc...etc... if (wordMimeTypes.Contains(file.ContentType)) { //word document } else { //not a word document } 

More readable than regex, because regex will become a pain in the ass when trying to make an expression for a dozen mime types

+3
source

DOC migration:

  • application / msword [official]
  • Application / Document
  • declaration / text
  • application /vnd.msword
  • app /vnd.ms word
  • application / winword
  • app / word
  • application / x-msw6
  • application / x-MSWord

happy regex'ing

Edit: According to @Dan Diplo, you should also check for .docx MIMEtypes

+6
source

if the content type is known (see Axarydax answer), why do you want to use regex?

+1
source

Take a look at the regexblid regex library.

It is also useful to know regexbuddy for validating and validating regular expressions.

0
source

Gumbo is right, it’s easier to check the file extension.

 Path.GetExtension(file.FileName) 
0
source

Source: https://habr.com/ru/post/1307019/


All Articles