Saturday, May 7, 2011

Retrieve all key-value pairs in a resource file


                                   Recently i have got one of the requirement in my project to retrieve all key/value pairs in a particular resource file.We know how to  retrieve any text value in any file knowing its key.A search revealed that I might be able to use ResXResourceReader class and iterate through the pairs; however the class is unfortunately located in the System.Windows.Forms.dll and I don't want to wire that dependency to my web app.

 So finally i have achieved it .Here is the solution.
public static IDictionary<object, object> GetResourceSet(string resourceKey, string resourceFile, CultureInfo cInfo)
{
string resourceValue = "";
IDictionary<object,object> resourceDictionary=null;
if (resourcesDirectory != string.Empty)
{
try
{
resourceDictionary = new Dictionary<object, object>();
impResx = System.Resources.ResourceManager.CreateFileBasedResourceManager(resourceFile, resourcesDirectory, null);
var ResourceSet = impResx.GetResourceSet(cInfo, false, true);
foreach (DictionaryEntry entry in ResourceSet)
{
resourceDictionary.Add(entry.Key, entry.Value);
}
}
catch (Exception ex)
{
throw ex;
}
}
}