2009-06-15 8 views
1

ASP.NET MVCアプリケーションでは、App_GlobalResourcesフォルダにある.resxファイルでローカライズされたテキストを管理します。私は、そのキーを知っているすべてのファイルのテキスト値を取得することができます。App_GlobalResourcesにあるリソースファイル内のすべてのキーと値のペアを取得する方法

ここでは、特定のリソースファイルのすべてのキーと値のペアを取得して、JavaScriptに結果を書きたいとします。検索の結果、ResXResourceReaderクラスを使用してペアを反復処理できることが明らかになりました。しかし、クラスは残念なことにSystem.Windows.Forms.dllにあり、私はその依存関係を私のWebアプリケーションに結びつけたくありません。この機能を実装できる他の方法はありますか?

答えて

2

解決策が見つかりました。 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()); 
    } 
} 
+0

優れた男!!!!!!!!!!!!!! –

0

他の回答はありません。 Forms.dllの参照が今のところ唯一の方法だと思われます。ここに私が思いついたコードがあります。

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()); 
    } 
} 
関連する問題