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?
Just build a collection - if it's small, just about any collection will do:
// Build the collection once (you may want a static readonly variable, for
// example).
List<string> list = new List<string> { ".jpg", ".jpeg", ".gif", ".bmp", ... };
// Later
if (list.Contains(extension))
{
...
}
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.
You can use !Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")
but internally somehow it will still loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With