tags:

views:

2133

answers:

5

I have an enum

public enum FileExtentions {
    mp3,
    mpeg
}

And I have a FileInfo of which I want to check if the extension is in the previous enum. I was hoping I could do a

FileExtensions.Any(e=>e.ToString().Equals(file.Extension));

But that would have been too awesome. Any ideas?

+4  A: 

While pressing submit I thought of the answer myself:

Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals("."+file.Extension))
borisCallens
But you can't mark your own entry as answer. But that's logical I guess.
borisCallens
file.Extension has the leading period - not the enum names. Shouldn't that be (f => ("." + f).Equals(file.Extension))?
Mark Brackett
A: 

You can do that with the System.Enum type:

string extension = Enum.GetName(typeof(FileExtensions), FileExtensions.mp3);

if (extension == file.Extension)
  // do something here

Update:

Ah, I misunderstood that you want to check the entire enum for the extension and not that a specific enum value matches the extension. In that case, your approach with GetNames() is the route - sorry you can't mark your own answer as accepted for your own question. ;-)

Jeff Donnici
That would check if my file has that exact extension. If I wanted to check that, I could aswell do if(file.Extension.equals(FileExtensions.Mp3.ToString()) [untested]
borisCallens
+1  A: 

You can extend the FileInfo type with the following extension method:

public static bool HasExtension(this FileInfo file)
{
    var ext = file.Extension.StartsWith(".") ? file.Extension.Substring(1) 
                                             : file.Extension;

    return Enum.GetNames(typeof(FileExtensions))
               .Any(f => f.Equals(ext));
}

and use it like:

bool hasExtension = file.HasExtension();
huseyint
A: 

What's the reason behind AnyEquals? Did you overlook Contains?

bool result = Enum.GetNames(typeof(FileExtensions)).Contains("mp3");
Konrad Rudolph
A: 

Enum.IsDefined will take a string containing the name of an enum value. The only ugliness is that you have to strip the leading period off of File.Extension and it's case sensitive:

Enum.IsDefined(typeof(FileExtension), file.Extension.Substring(1).ToLower())

Edit: Extension method goodness to get close to your desired syntax:

IEnumerable<string> GetNames(this Type t) {
   if (!t.IsEnum) throw new ArgumentException();

   return Enum.GetNames(t);
}

typeof(FileExtensions).GetNames().Any(e=>e.ToString().Equals(file.Extension));

Personally, though, I'd still rather the IsDefined route:

bool IsDefined(this Type t, string name) {
   if (!t.IsEnum) throw new ArgumentException();

   return Enum.IsDefined(t, name);
}

typeof(FileExtension).IsDefined(file.Extension);
Mark Brackett