如何从C#中的.resx文件读取字符串?请给我发指南。一步步
如何从C#中的.resx文件读取字符串?请给我发指南。一步步
Answers:
此示例来自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");
ResourceManager
在要加载外部资源时才需要。使用<Namespace>.Properties
代替。
ResourceManager
除非您是从外部资源加载,否则不需要。
对于大多数事情来说,假设您已经创建了一个项目(DLL,WinForms等),则只需使用项目名称空间,“资源”和资源标识符。例如:
假设一个项目名称空间: UberSoft.WidgetPro
您的resx包含:
您可以使用:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
试试这个,为我工作..简单
假设您的资源文件名为“ TestResource.resx”,然后您想动态地传递密钥,
string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);
添加命名空间
using System.Resources;
ResourceManager
在要加载外部资源时才需要。使用<Namespace>.Properties
代替。
打开.resx文件,并将“访问修饰符”设置为“公共”。
var <Variable Name> = Properties.Resources.<Resource Name>
假设.resx文件是使用Visual Studio在项目属性下添加的,则有一种更容易且错误更少的方式访问字符串。
然后访问该字符串就像:
var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
var exampleXmlString = resourceManager.GetString("exampleXml");
替换JoshCodes.Core.Testing.Unit
为项目的默认名称空间。
如果由于某种原因您无法将资源文件放入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。
将资源(名称:ResourceName和值:ResourceValue)添加到解决方案/程序集后,只需使用“ Properties.Resources.ResourceName”即可获取所需的资源。
我通过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创建Errors
的Errors.resx
文件在哪里,这MyErrorMessage
是关键。
我将资源文件直接添加到项目中,因此可以使用resx文件名访问其中的字符串。
示例:在Resource1.resx中,键“ resourceKey”->字符串“ dataString”。要获取字符串“ dataString”,我只需放入Resource1.resourceKey。
我可能不知道为什么没有这样做,但这对我有用。
从资源文件获取价值的最简单方法。在项目中添加资源文件。现在获取要添加到的字符串,例如我的情况是文本块(SilverLight)。也不需要添加任何名称空间。
txtStatus.Text = Constants.RefractionUpdateMessage;
这对我有用。说您有一个string.resx文件,其中包含字符串ok。阅读它
String varOk = My.Resources.strings.ok