Thursday, June 24, 2010

Get the value of static variable using reflection

I come to this code when i want to create new company for my application when new company is created i want to create whole folder structure again for uploading their documents or images with their company folder name.

Code

public static void CreateCorporateStructure(String _foldername)
    {
        try
        {
            Type typeOfclsConstant = typeof(clsConstant);
            FieldInfo[] objFieldInfo = typeOfclsConstant.GetFields();
            foreach (FieldInfo fi in objFieldInfo.Where(fi => fi.Name.Contains("_POSTFIX")))
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath("../" + clsConstant.COMPANY_PREFIXURL) + _foldername + Convert.ToString(fi.GetValue(null)).Substring(0, Convert.ToString(fi.GetValue(null)).Length - 1));
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Explaination

  • foreach (FieldInfo fi in objFieldInfo.Where(fi => fi.Name.Contains("_POSTFIX"))) is used to fetch number of fields from static class where variable name is ending with "_POSTFIX".
  • fi.GetValue(null)) which give the static value for field or variable.
Give some comment for above code if it is useful. If you find any suggestion than please reply.

No comments:

Post a Comment