c# – 如何在“网站”模式下使用ResourceManager?

我正在尝试为我正在使用的应用程序进行手动翻译. (已经有一个工作的LocalizationModule,但它工作狡猾,所以我不能使用< asp:Localize />标签.

通常使用ResourceManager,您应该将其用作Namespace.Folder.Resourcename(在应用程序中).目前我正在翻译现有的asp.net“网站”(不是网络应用程序,因此这里没有命名空间….).

资源位于文件夹名称“Locales / resources”中,其中包含“fr-ca.resx”和“en-us.resx”.

所以我使用了这样的代码:

public static string T(string search)
 {
  System.Resources.ResourceManager resMan = new System.Resources.ResourceManager( "Locales", System.Reflection.Assembly.GetExecutingAssembly(), null );

  var text = resMan.GetString(search, System.Threading.Thread.CurrentThread.CurrentCulture);

  if (text == null)
   return "null";
  else if (text == string.Empty)
   return "empty";
  else
   return text;
 }

在页面内我有类似的东西<%= Locale.T(“T_HOME”)%>

当我刷新时,我有这个:

Could not find any resources
appropriate for the specified culture
or the neutral culture. Make sure
“Locales.resources” was correctly
embedded or linked into assembly
“App_Code.9yopn1f7” at compile time,
or that all the satellite assemblies
required are loadable and fully
signed. Description: An unhandled
exception occurred during the
execution of the current web request.
Please review the stack trace for more
information about the error and where
it originated in the code.

Exception Details:
System.Resources.MissingManifestResourceException:
Could not find any resources
appropriate for the specified culture
or the neutral culture. Make sure
“Locales.resources” was correctly
embedded or linked into assembly
“App_Code.9yopn1f7” at compile time,
or that all the satellite assemblies
required are loadable and fully
signed.

Source Error:

Line 14:
System.Resources.ResourceManager
resMan = new
System.Resources.ResourceManager(
“Locales”,
System.Reflection.Assembly.GetExecutingAssembly(),
null ); Line 15: Line 16: var
text = resMan.GetString(search,
System.Threading.Thread.CurrentThread.CurrentCulture);
Line 17: Line 18: if (text == null)

Source File:
c:\inetpub\vhosts\galerieocarre.com\subdomains\dev\httpdocs\App_Code\Locale.cs
Line: 16

我甚至尝试使用Locales.fr-ca加载资源,或者只在这里使用fr-ca.

最佳答案 如果您无法访问HTTPContext,Marvin Smit的解决方案非常棒

const string ASSEMBLY_NAME = "App_GlobalResources";
const string RESOURCE_NAME = "Resources.MetaTagResource";
const string RESOURCE_MANAGER = "ResourceManager";

Assembly assembly = Assembly.Load(ASSEMBLY_NAME);
Type type = assembly.GetType(RESOURCE_NAME);
PropertyInfo propertyInfo = type.GetProperty(RESOURCE_MANAGER);
ResourceManager resourceManager = propertyInfo.GetValue(null, new object[] { }) as ResourceManager;
resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true);

但是如果您有权访问HTTPContext,只需使用HttpContext.GetGlobalResourceObject

string title = HttpContext.GetGlobalResourceObject("MetaTagResource", "Title").ToString();
string keywords = HttpContext.GetGlobalResourceObject("MetaTagResource", "keywords").ToString();
string description = HttpContext.GetGlobalResourceObject("MetaTagResource", "Description").ToString();
点赞