【问题标题】:read string from .resx file in C#从 C# 中的 .resx 文件中读取字符串
【发布时间】:2010-12-03 06:35:15
【问题描述】:

如何在 C# 中从 .resx 文件中读取字符串?请给我发送指南。循序渐进

【问题讨论】:

  • 看看this链接,应该会有帮助。
  • 为什么?如果他们对我的问题不满意,那我为什么要接受错误的建议?
  • 如果 .resx 文件是使用 Visual Studio 在项目属性下添加的,请参阅 my answer 以获得更简单且不易出错的访问字符串的方法。

标签: c# .net string .net-4.0


【解决方案1】:
  1. ResourceFileName.ResourceManager.GetString(ResourceFileName.Name)

2.return Resource.ResponseMsgSuccess;

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

这对我有用。 假设您有一个 strings.resx 文件,其中包含 ok 字符串。阅读它

String varOk = My.Resources.strings.ok

【讨论】:

    【解决方案3】:

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

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

    你的 resx 包含:

    你可以使用:

    Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
    

    【讨论】:

    • 非常感谢您的回答。
    • 谢谢,这应该被标记为答案。比这个问题的“答案”清晰得多。
    • 类型或命名空间不存在
    【解决方案4】:

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

    ResourceManager rm = new ResourceManager("param1",Assembly.GetExecutingAssembly());
    
    String str = rm.GetString("param2");
    

    param1 = "AssemblyName.ResourceFolderName.ResourceFileName"

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

    【讨论】:

      【解决方案5】:

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

      txtStatus.Text = Constants.RefractionUpdateMessage;
      

      Constants 是我在项目中的资源文件名

      【讨论】:

        【解决方案6】:

        将资源(名称:ResourceName 和值:ResourceValue)添加到解决方案/程序集后,您可以简单地使用“Properties.Resources.ResourceName”来获取所需的资源。

        【讨论】:

          【解决方案7】:

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

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

          可能有我不知道的不这样做的原因,但它对我有用。

          【讨论】:

            【解决方案8】:

            假设 .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”替换为您的字符串资源的名称。

            【讨论】:

            • 非常有帮助。谢谢。
            【解决方案9】:

            如果由于某种原因您不能将资源文件放在 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&lt;DictionaryEntry&gt;(); 并改用 LINQ。
            • 很难找到有关如何“读取、解析和加载”resx 文件的文章或帖子。您所得到的只是“使用 resx 作为项目字符串的容器”。谢谢你的回答!
            • 救了我的培根。这应该更高。
            【解决方案10】:

            在@JeffH 回答之后,我建议使用typeof() 而不是字符串程序集名称。

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

            【讨论】:

              【解决方案11】:

              我通过 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;
              

              其中Errors 是通过Visual Studio 创建的Errors.resx 文件,MyErrorMessage 是键。

              【讨论】:

              • 是的,我刚刚做的是今天的 VS2015。右键单击,添加“Resources”文件,任何键都变为“dottable”。因此,可以像 string scriptValue = MyResx.Script; 一样访问带有“Script”键的“MyResx.resx”
              • 在以上所有答案中,这是对我最有意义并为我工作的答案。谢谢。
              【解决方案12】:

              试试这个,对我有用..简单

              假设你的资源文件名为“TestResource.resx”,然后你想动态传递key,

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

              添加命名空间

              using System.Resources;
              

              【讨论】:

              • 您还可以选择指定文化 - 如果您想确保特定于文化的输出与默认值相矛盾,这很有用。例如TestResource.ResourceManager.GetString(description,new CultureInfo("en-GB"));
              • 我收到以下错误:“资源”不包含“GetString”的定义。
              • 当你想加载一个外部资源时,你只需要ResourceManager。请改用&lt;Namespace&gt;.Properties
              【解决方案13】:

              最简单的方法是:

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

              【讨论】:

                【解决方案14】:

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

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

                【讨论】:

                • 这种方法是否适用于多种资源文件(语言),导致我看到的每个地方都使用 ResourceManager 方法,我想知道我是否应该冒险使用这种方法......
                • 不起作用。我的资源文件不会在 Properties.Resources."my filename" 之后显示,即使它设置为 public
                【解决方案15】:

                这个例子来自MSDN page on ResourceManager.GetString()

                // 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");
                

                【讨论】:

                • 从我引用的 MSDN 页面:baseName 资源文件的根名称,不包括扩展名,但包括任何完全限定的命名空间名称。例如,名为 MyApplication.MyResource.en-US.resources 的资源文件的根名称是 MyApplication.MyResource。
                • items == 资源文件的命名空间
                • 不好的例子:你应该解释items是资源的命名空间+根类型
                • 当你想加载一个外部资源时,你只需要ResourceManager。请改用&lt;Namespace&gt;.Properties
                猜你喜欢
                • 1970-01-01
                • 2014-01-21
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-01-15
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多