Sunday, July 17, 2011

check string exists in the enum and convert string to an Enum

/// <summary>

/// File Type Enum - The extensions that our application

/// support to work.. check at the time of work with the

/// file.. e.g. read the file and save to database etc.

/// </summary>

 

enum FileTypes

{

     BMP ,

     JPG ,

     JPEG,

     GIF,

    TIFF

}

 

string fileExtension = Path.GetExtension(filePath).ToUpper();

       

//check string exists in the enum.. it will match the case also..

if (Enum.IsDefined(typeof(FileTypes),fileExtension.Trim('.')))

{

    //convert string to enum

    FileTypes  c = (FileTypes) Enum.Parse(typeof(FileTypes), "MOV", true);

}

 

Note: Enum.IsDefined() doesn't offer the ignoreCase parameter. If you don't

know whether the casing is right, it seems the only way to do the conversion is using

the Parse method and catching the ArgumentException.

No comments :

Post a Comment