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

Red*_*wan 89 .net c# string

如何在c#中读取.resx文件中的字符串?请寄给我指导.一步步

nat*_*ere 115

除非您从外部资源加载,否则不应该需要资源管理器.对于大多数事情,假设您已经创建了一个项目(DLL,WinForms,等等),您只需使用项目命名空间,"资源"和资源标识符.例如:

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

你的resx包含:

resx内容示例

你可以使用:

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您的回答。 (4认同)
  • 我认为这应该是公认的答案。 (3认同)

Jef*_*ffH 69

此示例来自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");
Run Code Online (Sandbox Code Playgroud)

  • 糟糕的例子:您应该解释项目是资源的名称空间+根类型 (6认同)
  • 在我引用的MSDN页面中:baseName没有扩展名但包含任何完全限定的命名空间名称的资源文件的根名称.例如,名为MyApplication.MyResource.en-US.resources的资源文件的根名称是MyApplication.MyResource. (4认同)
  • 仅当您想要加载外部资源时才需要“ResourceManager”。请改用“<Namespace>.Properties”。 (2认同)

小智 47

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

假设您的资源文件名是"TestResource.resx",并且您想要动态传递密钥,

string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);
Run Code Online (Sandbox Code Playgroud)

添加命名空间

using System.Resources;
Run Code Online (Sandbox Code Playgroud)


小智 27

打开.resx文件并将"Access Modifier"设置为Public.

var <Variable Name> = Properties.Resources.<Resource Name>
Run Code Online (Sandbox Code Playgroud)

  • 这个方法是否适用于多个资源文件(语言),导致我看到他们使用ResourceManager方法的每一个地方,我想知道我是否应该冒这种方式冒险,或者不... (2认同)
  • 不起作用。我的资源文件不会显示在 Properties.Resources."my filename" 之后,即使它设置为 public (2认同)

Jos*_*des 25

假设在项目属性下使用Visual Studio添加了.resx文件,则访问字符串的方法更容易且更不容易出错.

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

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
    
    Run Code Online (Sandbox Code Playgroud)
  4. 替换JoshCodes.Core.Testing.Unit为项目的默认命名空间.

  5. 将"exampleXml"替换为字符串资源的名称.

  • 很有帮助。谢谢。 (2认同)

You*_*jae 16

接下来是@JeffH的回答,我建议使用typeof()比字符串程序集名称.

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


WWC*_*WWC 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 "";
   }
Run Code Online (Sandbox Code Playgroud)


小智 8

将资源(Name:ResourceName和Value:ResourceValue)添加到解决方案/程序集后,只需使用"Properties.Resources.ResourceName"即可获取所需的资源.


Jus*_*les 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,我就能做到:

string message = Errors.MyErrorMessage;
Run Code Online (Sandbox Code Playgroud)

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


Eli*_*ron 5

我直接将我的资源文件添加到我的项目中,因此我能够使用resx文件名访问内部的字符串.

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

可能有理由不这样做,我不知道,但它对我有用.