如何从C#中的特定资源文件中获取字符串资源

时间:2014-10-27 15:37:41

标签: c# .net asp.net-mvc localization

在我们项目 的某些情况下,我们必须忽略应用程序的当前文化 并获得英语资源。

基本上我们就像所有语言一样

<label>@ModelEntities.Properties.Resource.Gender</label>

怎么可能只用英文?

我假设我们以某种方式创建了对Resource.resx的引用?

我用过

 ResourceManager rm = new ResourceManager("Resource.Strings",
                     Assembly.GetAssembly(typeof(ModelEntities.Properties.Resource))); 
  var s = rm.GetString("Age");

但似乎没有用。

谢谢!

4 个答案:

答案 0 :(得分:4)

您可以使用资源管理器类click here for more info about the class

System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-GB"); 
ResourceManager resourceManager = new ResourceManager("YourResource", Assembly.GetExecutingAssembly()); 
string bodyResource = resourceManager.GetString("yourText", ci);

答案 1 :(得分:3)

我找到了可行的解决方案。

首先,我们的资源文件结尾如

  

Resource.resx

而不是Resources.resx

第二,我们在单独的程序集中拥有资源: ModelEntities

所以工作代码如下:

var resourceManager = new ResourceManager(typeof(ModelEntities.Properties.Resource)); 
var genderString = resourceManager.GetString("Gender", ci);

答案 2 :(得分:3)

一种简单的方法:

YorResourceName.ResourceManager.GetString("ResourceKeyName", System.Globalization.CultureInfo.GetCultureInfo("en-US"))

答案 3 :(得分:2)

文件夹结构:

MyApplicationSolution
/资源
/Resource.resx

public static string GetLocalisedRes(string resourceName = "", string resourceNameKey = "")
    {
        string translate = string.Empty;
        string baseName = "YourNameSpace.Resources." + resourceName + "";

        try
        {
            Type resType = Type.GetType(baseName);
            ResourceManager rm = new ResourceManager(baseName, resType.Assembly);
            translate = rm.GetString(resourceNameKey);
        }
        catch {
            translate = string.Empty;
        }
        return translate;
    }

用法

    var age = GetLocalisedRes("Resource", "Age");

这对我有用

相关问题