Chaddeus
Chaddeus

Reputation: 13366

Is there a way to check if a string is not equal to multiple different strings?

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?

Upvotes: 5

Views: 10830

Answers (8)

SHS
SHS

Reputation: 149

You can use switch statement to validate file extension:

protected bool IsValidExtension(string extension)
{
  switch (extension.ToLower())
  {
    case ".jpg":
    case ".jpeg":
    case ".gif":
    case ".png":
    case ".bmp":
      return true;

    default:
      return false;
  }
}

Upvotes: 0

Matt
Matt

Reputation: 6953

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

        public static bool In<T>(this T t, IEnumerable<T> enumerable)
        {
            foreach (T item in enumerable)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

        public static bool In<T>(this T t, params T[] items)
        {
            foreach (T item in items)
            {
                if (item.Equals(t))
                { return true; }
            }
            return false;
        }

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:

if (myString == "val1" ||
   myString == "val2" ||
   myString == "val3" ||
   myString == "val4" ||
   myString == "val5")
   {
      //Do something
   }

Upvotes: 3

Christian
Christian

Reputation: 3972

Regular Expression.

    string fx = "jpg";
    if (!Regex.IsMatch(fx, "^\.?(jpg|jpeg|gif|png|bmp)$", RegexOptions.IgnoreCase))
    {

    }

also, to get the file extension, use

string fn= file.FileName;
if (fn.Contains("\\")) 
    fn= fn.Substring(fn.LastIndexOf("\\") + 1);

string fx = fn.Substring(0, fn.LastIndexOf('.'));

Upvotes: 0

Peter Perh&#225;č
Peter Perh&#225;č

Reputation: 20782

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.

Upvotes: 1

fixagon
fixagon

Reputation: 5566

You can use !Regex.IsMatch(extension, "^\.(jpg|jpeg|gif|png|bmp)$")

but internally somehow it will still loop

Upvotes: 5

It will require a loop, but you can do this with LINQ (hides the loop)

ie:

using System.Linq;

private readonly string[] _matches = new[] { ".jpg", ".bmp", ".png", ".gif", ".bmp" };    

// Assumes extension is in the format ".jpg", "bmp", so trim the
// whitespace from start and end
public bool IsMatch(string extension)
{
     return _matches.Contains(extension);
}

It could also be done with Regex but I'm no regex wizz so I'll leave that to another poster :)

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500855

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.

Upvotes: 28

Svish
Svish

Reputation: 158071

Stick the extensions in a collection, then check if the extension of your file is in that collection.

Upvotes: 3

Related Questions