Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to check file content type is .doc or not?

Tags:

c#

regex

When i use a file upload i use to check file contenttype 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 is an image or not... How to check it is a word(.doc/.docx) document or not using c#...

like image 854
ACP Avatar asked Dec 29 '22 20:12

ACP


2 Answers

DOC's mimetype is:

  • application/msword [official]
  • application/doc
  • appl/text
  • application/vnd.msword
  • application/vnd.ms-word
  • application/winword
  • application/word
  • application/x-msw6
  • application/x-msword

happy regex'ing

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

like image 171
Axarydax Avatar answered Dec 31 '22 15:12

Axarydax


For example using Axarydax answer: (so no docx mime check)

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 a expression for a dozen of mime types

like image 40
RvdK Avatar answered Dec 31 '22 15:12

RvdK