有没有办法检查一个字符串是否不等于多个不同的字符串?
我想通过文件扩展名验证文件上传器。如果文件扩展名不等于 .jpg、.jpeg、.gif、.png、.bmp,则抛出验证错误。
有没有办法在不循环遍历每种类型的情况下做到这一点?
I want to validate a file uploader, by file extension. If the file extension is not equal to .jpg, .jpeg, .gif, .png, .bmp then throw validation error.
Is there a way to do this without looping through each type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
只需构建一个集合 - 如果它很小,几乎任何集合都可以:
当然,这确实会循环所有值 - 但对于小型集合,这应该不会太昂贵。对于大型字符串集合,您需要使用诸如
HashSet
之类的东西,这将提供更有效的查找。Just build a collection - if it's small, just about any collection will do:
That does loop over all the values of course - but for small collections, that shouldn't be too expensive. For a large collection of strings you'd want to use something like
HashSet<string>
instead, which would provide a more efficient lookup.您可以使用
!Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")
但在内部不知何故它仍然会循环
You can use
!Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")
but internally somehow it will still loop
将扩展名粘贴到集合中,然后检查文件的扩展名是否在该集合中。
Stick the extensions in a collection, then check if the extension of your file is in that collection.
它将需要一个循环,但您可以使用 LINQ 来完成此操作(隐藏循环),
即:
也可以使用 Regex 来完成,但我不是 regex wizz,所以我将把它留给另一位海报:)
It will require a loop, but you can do this with LINQ (hides the loop)
ie:
It could also be done with Regex but I'm no regex wizz so I'll leave that to another poster :)
使用以下 2 个扩展。我在 CodeProject 上的一篇文章中介绍了它们。干得好:
http://www.codeproject.com/KB/dotnet/MBGExtensionsLibrary.aspx
当然,它仍然需要一个循环,但好处是您不必做这项工作。这也意味着您不必编写如下代码:
Use the following 2 extensions. I wrote about them in an article on CodeProject. Here you go:
http://www.codeproject.com/KB/dotnet/MBGExtensionsLibrary.aspx
Of course it still requires a loop, but the good thing is you don't have to do that work. It also means you don't have to write code like this:
StackOverflow 上已经有答案了。 此处
但我建议您采取构建扩展列表的方式,然后再次检查每个扩展。正则表达式的成本会更高,并且内部的作用大致相同。
There's an answer to that on StackOverflow already. HERE
But I'd suggest you take the path of constructing a list of extensions and then checking agains each one of those. Regex would be more costly than that and would internally do roughly the same.
正则表达式。
另外,要获取文件扩展名,请使用
Regular Expression.
also, to get the file extension, use
您可以使用 switch 语句来验证文件扩展名:
You can use switch statement to validate file extension: