[英]regular expression to check file content type is .doc or not?
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#... 这返回我的文件是图像与否...如何检查它是一个单词(.doc / .docx)文件或不使用c#...
DOC's mimetype is: DOC的mimetype是:
happy regex'ing 快乐的正则表达
Edit:According to @Dan Diplo, you should also check for .docx's MIMEtypes 编辑:根据@Dan Diplo,您还应该检查.docx的MIME类型
For example using Axarydax answer: (so no docx mime check) 例如使用Axarydax答案:(所以没有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 a expression for a dozen of mime types 比正则表达式更具可读性,因为在尝试为十几种mime类型创建表达式时,正则表达式会变得很麻烦
如果内容类型是已知的(请参阅Axarydax答案),为什么要使用正则表达式?
Take a look at regexblid A library with regular expression. 看看regexblid带有正则表达式的库。
Also good to know, regexbuddy can be used to validate and test regular expressions. 另外很高兴知道, regexbuddy可用于验证和测试正则表达式。
Gumbo是对的,检查文件的扩展名可能更容易。
Path.GetExtension(file.FileName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.