Friday, November 23, 2012

Iterate in Resource File and fetch value of the matching String

Hi Reader,

Recently I came across a requirement where I need to iterate in a resource file added in my ASP.NET Project and fetch the matching value of a specific string.
Exact requirement goes like this, I have to return a Token Key ( Value ) of a Domain Name ( String Name) in a resx file. If the URL contains the Domain Name which is added in resx file then respective Token Key is fetched.
So we need to loop in the resx file, look for the containing string and if it matches then returns the value.
Code goes like this :


ResourceManager resourceManager = new ResourceManager("Resources.SiteUrl", System.Reflection.Assembly.Load("App_GlobalResources"));
                        
                        ResourceSet resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
                        foreach (DictionaryEntry entry in resourceSet)
                        {
                            object resourceKey = entry.Key;
                            object resource = entry.Value;
                            if (returnUrl.Contains(resourceKey.ToString()))
                            {
                                DomainName = resourceKey.ToString();
                                Token = resource.ToString();
                            }
                        }
                        if (DomainName != null)
                        {
                            if (returnUrl.Contains(DomainName))
                            {
                                returnUrl = string.Format("{0}/_layouts/Authenticate.aspx?{1}={2}", returnUrl, Token, authCookie);
                            }
                        }


In Above code , ResourceManager Object is created to that looks up resources contained in files with the specified root name in the given assembly. 
ResourceSet Stores all the resources localized for one particular culture, ignoring all other cultures, including any fallback rules.

DictonaryEntry will get the key value pair of each item in the resource file.

Hope this helps !!



No comments:

Post a Comment