views:

578

answers:

2

In my ASP.NET MVC application, I manage localized texts in .resx files located in App_GlobalResources folder. I am able to retrieve any text value in any file knowing its key.

Now, I want to retrieve all key/value pairs in a particular resource file in order to write the result to some JavaScript. 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. Is there any other way I can implement this feature?

A: 

Okay, no other answer. Seems like referencing Forms.dll is the only way right now. Here's the code I came up with.

public class ScriptController : BaseController
{
    private const string ResxPathTemplate = "~/App_GlobalResources/script{0}.resx";
    public ActionResult GetResources()
    {
        var resxPath = Server.MapPath(string.Format(ResxPathTemplate, string.Empty));
        var resxPathLocalized = Server.MapPath(string.Format(ResxPathTemplate, 
            "." + CurrentCulture));
        var pathToUse = System.IO.File.Exists(resxPathLocalized)
                            ? resxPathLocalized
                            : resxPath;

        var builder = new StringBuilder();
        using (var rsxr = new ResXResourceReader(pathToUse))
        {
            builder.Append("var resources = {");
            foreach (DictionaryEntry entry in rsxr)
            {
                builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
            }
            builder.Append("};");
        }
        Response.ContentType = "application/x-javascript";
        Response.ContentEncoding = Encoding.UTF8;
        return Content(builder.ToString());
    }
}
Buu Nguyen
+1  A: 

I've found the solution. Now no need to reference Forms.dll.

public class ScriptController : BaseController
{
    private static readonly ResourceSet ResourceSet = 
        Resources.Controllers.Script.ResourceManager.GetResourceSet(CurrentCulture, true, true);

    public ActionResult GetResources()
    {
        var builder = new StringBuilder();
        builder.Append("var LocalizedStrings = {");
        foreach (DictionaryEntry entry in ResourceSet)
        {
            builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value);
        }
        builder.Append("};");
        Response.ContentType = "application/x-javascript";
        Response.ContentEncoding = Encoding.UTF8;
        return Content(builder.ToString());
    }
}
Buu Nguyen
excellent man!!!!!!!!!!!!!!
Muhammad Akhtar