从 C# 中的 .resx 文件读取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1508570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
read string from .resx file in C#
提问by Red Swan
How to read the string from .resx file in c#? please send me guidelines . step by step
如何从 C# 中的 .resx 文件中读取字符串?请寄给我指导方针。一步步
采纳答案by JeffH
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");
回答by SasHok.Tk
Open .resx file and set "Access Modifier" to Public.
打开 .resx 文件并将“访问修饰符”设置为公共。
var <Variable Name> = Properties.Resources.<Resource Name>
回答by nathanchere
ResourceManager
shouldn't be needed unless you're loading from an externalresource.
For most things, say you've created a project (DLL, WinForms, whatever) you just use the project namespace, "Resources" and the resource identifier. eg:
ResourceManager
除非您从外部资源加载,否则不需要。
对于大多数情况,假设您已经创建了一个项目(DLL、WinForms 等),您只需使用项目命名空间、“资源”和资源标识符。例如:
Assuming a project namespace: UberSoft.WidgetPro
假设一个项目命名空间: UberSoft.WidgetPro
And your resx contains:
你的 resx 包含:
You can just use:
你可以只使用:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
回答by Joshcodes
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.
假设 .resx 文件是使用 Visual Studio 在项目属性下添加的,则访问字符串的方式更简单且不易出错。
- Expanding the .resx file in the Solution Explorer should show a .Designer.cs file.
- When opened, the .Designer.cs file has a Properties namespace and an internal class. For this example assume the class is named Resources.
Accessing the string is then as easy as:
var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager; var exampleXmlString = resourceManager.GetString("exampleXml");
Replace
JoshCodes.Core.Testing.Unit
with the project's default namespace.- Replace "exampleXml" with the name of your string resource.
- 在解决方案资源管理器中展开 .resx 文件应该会显示一个 .Designer.cs 文件。
- 打开时,.Designer.cs 文件有一个 Properties 命名空间和一个内部类。对于此示例,假设类名为 Resources。
访问字符串就像这样简单:
var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager; var exampleXmlString = resourceManager.GetString("exampleXml");
替换
JoshCodes.Core.Testing.Unit
为项目的默认命名空间。- 将“exampleXml”替换为您的字符串资源的名称。
回答by Nomad77
The easiest way to do this is:
最简单的方法是:
- Create an App_GlobalResources system folder and add a resource file to it e.g. Messages.resx
- Create your entries in the resource file e.g. ErrorMsg = This is an error.
- Then to access that entry: string errormsg = Resources.Messages.ErrorMsg
- 创建一个 App_GlobalResources 系统文件夹并向其中添加一个资源文件,例如 Messages.resx
- 在资源文件中创建您的条目,例如 ErrorMsg = 这是一个错误。
- 然后访问该条目: string errormsg = Resources.Messages.ErrorMsg
回答by Muru Bakthavachalam
Try this, works for me.. simple
试试这个,对我有用..简单
Assume that your resource file name is "TestResource.resx", and you want to pass key dynamically then,
假设你的资源文件名是“TestResource.resx”,然后你想动态传递key,
string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);
Add Namespace
添加命名空间
using System.Resources;
回答by Justin Skiles
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 文件。这创建了一个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);
}
}
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 创建Errors
的Errors.resx
文件在哪里,MyErrorMessage
是关键。
回答by Youngjae
Followed by @JeffH answer, I recommend to use typeof()
than string assembly name.
其次是@JeffH 的回答,我建议使用typeof()
比字符串程序集名称。
var rm = new ResourceManager(typeof(YourAssembly.Properties.Resources));
string message = rm.GetString("NameOfKey", CultureInfo.CreateSpecificCulture("ja-JP"));
回答by WWC
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 "";
}
回答by Eliezer Miron
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.resx 中,键“resourceKey”-> 字符串“dataString”。为了得到字符串“dataString”,我只放了Resource1.resourceKey。
There may be reasons not to do this that I don't know about, but it worked for me.
可能有我不知道的不这样做的原因,但它对我有用。