从C#中的.resx文件读取字符串


99

如何从C#中的.resx文件读取字符串?请给我发指南。一步步


看看这个链接,它会有所帮助。
Adriaan Stander

15
为什么?如果他们对我的问题不满意,那为什么我必须接受错误的建议?
Red Swan 2010年

1
如果.resx文件是使用Visual Studio在项目属性下添加的,请参阅我的回答,以更轻松,更不易出错的方式访问字符串。
Joshcodes 2013年

Answers:


75

此示例来自ResourceManager.GetString()上MSDN页面

// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());

// Retrieve the value of the string resource named "welcome".
// The resource manager will retrieve the value of the  
// localized resource using the caller's current culture setting.
String str = rm.GetString("welcome");

4
在MSDN页面上,我引用了:baseName资源文件的根名称,不带扩展名,但包括任何完全限定的名称空间名称。例如,名为MyApplication.MyResource.en-US.resources的资源文件的根名称是MyApplication.MyResource。
JeffH 2014年

1
项目==资源文件的命名空间

7
较差的示例:您应说明项目是资源的名称空间+根类型
ActiveX

ResourceManager在要加载外部资源时才需要。使用<Namespace>.Properties代替。
Yousha Aleayoub

131

ResourceManager除非您是从外部资源加载,否则不需要。
对于大多数事情来说,假设您已经创建了一个项目(DLL,WinForms等),则只需使用项目名称空间,“资源”和资源标识符。例如:

假设一个项目名称空间: UberSoft.WidgetPro

您的resx包含:

resx内容示例

您可以使用:

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED

4
非常感谢您的回答。
Vaishali

1
谢谢,这应该标记为答案。比这个问题的“答案”清楚得多。
Jeroen Jonkman

类型或名称空间不存在
Paul McCarthy

53

试试这个,为我工作..简单

假设您的资源文件名为“ TestResource.resx”,然后您想动态地传递密钥,

string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);

添加命名空间

using System.Resources;

您还可以选择指定区域性-如果要确保特定于区域性的输出与默认设置相矛盾,则很有用。例如TestResource.ResourceManager.GetString(description,new CultureInfo(“ en-GB”));
伊恩

我收到以下错误:'资源'不包含'GetString'的定义。
Lechucico

ResourceManager在要加载外部资源时才需要。使用<Namespace>.Properties代替。
Yousha Aleayoub

29

打开.resx文件,并将“访问修饰符”设置为“公共”。

var <Variable Name> = Properties.Resources.<Resource Name>

2
此方法是否与多个资源文件(语言)一起使用,导致我看上去他们使用的每个地方都使用ResourceManager方法,并且我想知道是否应该冒险使用这种方式...
deadManN 2015年

1
不起作用。即使设置为public,我的资源文件也不会显示在Properties.Resources。“我的文件名”之后
user1804084

27

假设.resx文件是使用Visual Studio在项目属性下添加的,则有一种更容易且错误更少的方式访问字符串。

  1. 在解决方案资源管理器中展开.resx文件应显示一个.Designer.cs文件。
  2. 打开后,.Designer.cs文件将具有“属性”命名空间和一个内部类。对于此示例,假设该类名为Resources。
  3. 然后访问该字符串就像:

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
  4. 替换JoshCodes.Core.Testing.Unit为项目的默认名称空间。

  5. 用字符串资源的名称替换“ exampleXml”。

3
很有帮助。谢谢。
ejmin

16

其次是@JeffH回答,我建议使用typeof()比字符串程序集名称。

    var rm = new ResourceManager(typeof(YourAssembly.Properties.Resources));
    string message = rm.GetString("NameOfKey", CultureInfo.CreateSpecificCulture("ja-JP"));

10

如果由于某种原因您无法将资源文件放入App_GlobalResources中,则可以直接使用ResXResourceReader或XML Reader打开资源文件。

以下是使用ResXResourceReader的示例代码:

   public static string GetResourceString(string ResourceName, string strKey)
   {


       //Figure out the path to where your resource files are located.
       //In this example, I'm figuring out the path to where a SharePoint feature directory is relative to a custom SharePoint layouts subdirectory.  

       string currentDirectory = Path.GetDirectoryName(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"]));

       string featureDirectory = Path.GetFullPath(currentDirectory + "\\..\\..\\..\\FEATURES\\FEATURENAME\\Resources");

       //Look for files containing the name
       List<string> resourceFileNameList = new List<string>();

       DirectoryInfo resourceDir = new DirectoryInfo(featureDirectory);

       var resourceFiles = resourceDir.GetFiles();

       foreach (FileInfo fi in resourceFiles)
       {
           if (fi.Name.Length > ResourceName.Length+1 && fi.Name.ToLower().Substring(0,ResourceName.Length + 1) == ResourceName.ToLower()+".")
           {
               resourceFileNameList.Add(fi.Name);

           }
        }

       if (resourceFileNameList.Count <= 0)
       { return ""; }


       //Get the current culture
       string strCulture = CultureInfo.CurrentCulture.Name;

       string[] cultureStrings = strCulture.Split('-');

       string strLanguageString = cultureStrings[0];


       string strResourceFileName="";
       string strDefaultFileName = resourceFileNameList[0];
       foreach (string resFileName in resourceFileNameList)
       {
           if (resFileName.ToLower() == ResourceName.ToLower() + ".resx")
           {
               strDefaultFileName = resFileName;
           }

           if (resFileName.ToLower() == ResourceName.ToLower() + "."+strCulture.ToLower() + ".resx")
           {
               strResourceFileName = resFileName;
               break;
           }
           else if (resFileName.ToLower() == ResourceName.ToLower() + "." + strLanguageString.ToLower() + ".resx")
           {
               strResourceFileName = resFileName;
               break;
           }
       }

       if (strResourceFileName == "")
       {
           strResourceFileName = strDefaultFileName;
       }



       //Use resx resource reader to read the file in.
       //https://msdn.microsoft.com/en-us/library/system.resources.resxresourcereader.aspx

       ResXResourceReader rsxr = new ResXResourceReader(featureDirectory + "\\"+ strResourceFileName);         

       //IDictionaryEnumerator idenumerator = rsxr.GetEnumerator();
       foreach (DictionaryEntry d in rsxr)
       {
           if (d.Key.ToString().ToLower() == strKey.ToLower())
           {
               return d.Value.ToString();
           }
       }


       return "";
   }

谢谢,请注意,您必须添加System.Windows.Forms要使用的参考System.Resources.ResXResourceReader。此外,您可以var enumerator = rsxr.OfType<DictionaryEntry>();改为使用LINQ。
2015年

很难找到有关如何“读取,解析和加载” resx文件的文章或帖子。您得到的只是“将resx用作项目字符串的容器”。感谢您的回答!
西蒙妮


7

我通过Visual Studio添加了.resx文件。这创建了一个designer.cs具有属性的文件,可立即返回我想要的任何键的值。例如,这是从设计器文件中自动生成的一些代码。

/// <summary>
///   Looks up a localized string similar to When creating a Commissioning change request, you must select valid Assignees, a Type, a Component, and at least one (1) affected unit..
/// </summary>
public static string MyErrorMessage {
    get {
        return ResourceManager.GetString("MyErrorMessage", resourceCulture);
    }
}

这样,我就能简单地做到:

string message = Errors.MyErrorMessage;

通过Visual Studio创建ErrorsErrors.resx文件在哪里,这MyErrorMessage是关键。


是的,我今天刚做的就是VS2015。右键单击,添加“资源”文件,然后任何键都将变为“ dottable”。因此,可以像字符串scriptValue = MyResx.Script;这样访问带有键“ Script”的“ MyResx.resx”;
emery.noel

5

我将资源文件直接添加到项目中,因此可以使用resx文件名访问其中的字符串。

示例:在Resource1.resx中,键“ resourceKey”->字符串“ dataString”。要获取字符串“ dataString”,我只需放入Resource1.resourceKey。

我可能不知道为什么没有这样做,但这对我有用。


3

最简单的方法是:

  1. 创建一个App_GlobalResources系统文件夹并向其中添加资源文件,例如Messages.resx
  2. 在资源文件中创建条目,例如ErrorMsg =这是一个错误。
  3. 然后访问该条目:字符串errormsg = Resources.Messages.ErrorMsg

2

从资源文件获取价值的最简单方法。在项目中添加资源文件。现在获取要添加到的字符串,例如我的情况是文本块(SilverLight)。也不需要添加任何名称空间。

txtStatus.Text = Constants.RefractionUpdateMessage;

常量是我在项目中的资源文件名。这是我的资源文件的样子


0

创建资源管理器以检索资源。

ResourceManager rm = new ResourceManager("param1",Assembly.GetExecutingAssembly());

String str = rm.GetString("param2");

param1 =“ AssemblyName.ResourceFolderName.ResourceFileName”

param2 =要从资源文件中检索的字符串的名称


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.