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

时间:2021-11-27 21:23:14

How to read the string from .resx file in c#? please send me guidelines . step by step

如何从c# .resx文件中读取字符串?请发给我指导意见。一步一步

11 个解决方案

#1


68  

This example is from the MSDN page on ResourceManager.GetString():

这个例子来自于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");

#2


67  

Resource manager shouldn't be needed unless you're loading from an external resource. For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:

资源管理器应该不需要,除非您正在从外部资源加载。对于大多数情况,假设您已经创建了一个项目(DLL、WinForms等等),那么您只需使用项目名称空间、“Resources”和资源标识符。例如:

Assuming a project namespace: UberSoft.WidgetPro

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

And your resx contains:

和你resx包含:

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

You can just use:

你可以使用:

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED

#3


40  

Try this, works for me.. simple

试试这个,对我有用。简单的

Assume that your resource file name is "TestResource.resx", and you want to pass key dynamically then,

假设您的资源文件名是“TestResource”。然后你想动态传递key,

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

Add Namespace

添加名称空间

using System.Resources;

#4


24  

Open .resx file and set "Access Modifier" to Public.

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

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

#5


20  

Assuming the .resx file was added using Visual Studio under the project properties, there is an easier and less error prone way to access the string.

假设在项目属性下使用Visual Studio添加.resx文件,有一种更容易、更少出错的方法来访问字符串。

  1. Expanding the .resx file in the Solution Explorer should show a .Designer.cs file.
  2. 在解决方案资源管理器中展开.resx文件应该显示. designer。cs文件。
  3. When opened, the .Designer.cs file has a Properties namespace and an internal class. For this example assume the class is named Resources.
  4. 当打开,.Designer。cs文件有一个属性名称空间和一个内部类。对于本例,假设类被命名为Resources。
  5. Accessing the string is then as easy as:

    因此,访问字符串非常简单:

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
    
  6. Replace JoshCodes.Core.Testing.Unit with the project's default namespace.

    取代JoshCodes.Core.Testing。使用项目的默认名称空间的单元。

  7. Replace "exampleXml" with the name of your string resource.
  8. 将“exampleXml”替换为字符串资源的名称。

#6


13  

Followed by @JeffH answer, I recommend to use typeof() than string assembly name.

在@JeffH后面,我建议使用typeof()而不是string程序集名称。

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

#7


8  

If for some reason you can't put your resources files in App_GlobalResources, then you can open resources files directly using ResXResourceReader or an XML Reader.

如果由于某种原因,您不能将资源文件放在App_GlobalResources中,那么您可以使用ResXResourceReader或XML Reader直接打开资源文件。

Here's sample code for using the ResXResourceReader:

下面是使用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 "";
   }

#8


7  

Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.

一旦您向解决方案/程序集添加了一个资源(名称:ResourceName和值:ResourceValue),您就可以简单地使用“property . resources”。获取所需的资源。

#9


5  

I added the .resx file via Visual Studio. This created a designer.cs file with properties to immediately return the value of any key I wanted. For example, this is some auto-generated code from the designer file.

我通过Visual Studio添加了.resx文件。这创建了一个设计师。具有属性的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);
    }
}

That way, I was able to simply do:

这样,我就可以简单地做到:

string message = Errors.MyErrorMessage;

Where Errors is the Errors.resx file created through Visual Studio and MyErrorMessage is the key.

错误就是错误。通过Visual Studio和MyErrorMessage创建的resx文件是关键。

#10


4  

I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.

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

Example: in Resource1.resx, key "resourceKey" -> string "dataString". To get the string "dataString", I just put Resource1.resourceKey.

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

There may be reasons not to do this that I don't know about, but it worked for me.

也许有理由不去做我不知道的事情,但它对我起作用了。

#11


2  

The easiest way to do this is:

最简单的方法是:

  1. Create an App_GlobalResources system folder and add a resource file to it e.g. Messages.resx
  2. 创建一个App_GlobalResources系统文件夹,并向其中添加一个资源文件,例如Messages.resx
  3. Create your entries in the resource file e.g. ErrorMsg = This is an error.
  4. 在资源文件中创建条目,例如ErrorMsg =这是错误。
  5. Then to access that entry: string errormsg = Resources.Messages.ErrorMsg
  6. 然后访问该条目:string errormsg = Resources.Messages.ErrorMsg

#1


68  

This example is from the MSDN page on ResourceManager.GetString():

这个例子来自于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");

#2


67  

Resource manager shouldn't be needed unless you're loading from an external resource. For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:

资源管理器应该不需要,除非您正在从外部资源加载。对于大多数情况,假设您已经创建了一个项目(DLL、WinForms等等),那么您只需使用项目名称空间、“Resources”和资源标识符。例如:

Assuming a project namespace: UberSoft.WidgetPro

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

And your resx contains:

和你resx包含:

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

You can just use:

你可以使用:

Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED

#3


40  

Try this, works for me.. simple

试试这个,对我有用。简单的

Assume that your resource file name is "TestResource.resx", and you want to pass key dynamically then,

假设您的资源文件名是“TestResource”。然后你想动态传递key,

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

Add Namespace

添加名称空间

using System.Resources;

#4


24  

Open .resx file and set "Access Modifier" to Public.

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

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

#5


20  

Assuming the .resx file was added using Visual Studio under the project properties, there is an easier and less error prone way to access the string.

假设在项目属性下使用Visual Studio添加.resx文件,有一种更容易、更少出错的方法来访问字符串。

  1. Expanding the .resx file in the Solution Explorer should show a .Designer.cs file.
  2. 在解决方案资源管理器中展开.resx文件应该显示. designer。cs文件。
  3. When opened, the .Designer.cs file has a Properties namespace and an internal class. For this example assume the class is named Resources.
  4. 当打开,.Designer。cs文件有一个属性名称空间和一个内部类。对于本例,假设类被命名为Resources。
  5. Accessing the string is then as easy as:

    因此,访问字符串非常简单:

    var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
    var exampleXmlString = resourceManager.GetString("exampleXml");
    
  6. Replace JoshCodes.Core.Testing.Unit with the project's default namespace.

    取代JoshCodes.Core.Testing。使用项目的默认名称空间的单元。

  7. Replace "exampleXml" with the name of your string resource.
  8. 将“exampleXml”替换为字符串资源的名称。

#6


13  

Followed by @JeffH answer, I recommend to use typeof() than string assembly name.

在@JeffH后面,我建议使用typeof()而不是string程序集名称。

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

#7


8  

If for some reason you can't put your resources files in App_GlobalResources, then you can open resources files directly using ResXResourceReader or an XML Reader.

如果由于某种原因,您不能将资源文件放在App_GlobalResources中,那么您可以使用ResXResourceReader或XML Reader直接打开资源文件。

Here's sample code for using the ResXResourceReader:

下面是使用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 "";
   }

#8


7  

Once you add a resource (Name: ResourceName and Value: ResourceValue) to the solution/assembly, you could simply use "Properties.Resources.ResourceName" to get the required resource.

一旦您向解决方案/程序集添加了一个资源(名称:ResourceName和值:ResourceValue),您就可以简单地使用“property . resources”。获取所需的资源。

#9


5  

I added the .resx file via Visual Studio. This created a designer.cs file with properties to immediately return the value of any key I wanted. For example, this is some auto-generated code from the designer file.

我通过Visual Studio添加了.resx文件。这创建了一个设计师。具有属性的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);
    }
}

That way, I was able to simply do:

这样,我就可以简单地做到:

string message = Errors.MyErrorMessage;

Where Errors is the Errors.resx file created through Visual Studio and MyErrorMessage is the key.

错误就是错误。通过Visual Studio和MyErrorMessage创建的resx文件是关键。

#10


4  

I added my resource file to my project directly, and so I was able to access the strings inside just fine with the resx file name.

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

Example: in Resource1.resx, key "resourceKey" -> string "dataString". To get the string "dataString", I just put Resource1.resourceKey.

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

There may be reasons not to do this that I don't know about, but it worked for me.

也许有理由不去做我不知道的事情,但它对我起作用了。

#11


2  

The easiest way to do this is:

最简单的方法是:

  1. Create an App_GlobalResources system folder and add a resource file to it e.g. Messages.resx
  2. 创建一个App_GlobalResources系统文件夹,并向其中添加一个资源文件,例如Messages.resx
  3. Create your entries in the resource file e.g. ErrorMsg = This is an error.
  4. 在资源文件中创建条目,例如ErrorMsg =这是错误。
  5. Then to access that entry: string errormsg = Resources.Messages.ErrorMsg
  6. 然后访问该条目:string errormsg = Resources.Messages.ErrorMsg