Làm cách nào để đọc chuỗi từ tệp .resx trong c #? xin vui lòng gửi cho tôi hướng dẫn. từng bước một
Làm cách nào để đọc chuỗi từ tệp .resx trong c #? xin vui lòng gửi cho tôi hướng dẫn. từng bước một
Câu trả lời:
Ví dụ này là từ trang MSDN trên 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");
ResourceManager
khi bạn muốn tải một tài nguyên Bên ngoài. Sử dụng <Namespace>.Properties
thay thế.
ResourceManager
không cần thiết trừ khi bạn đang tải từ tài nguyên bên ngoài .
Đối với hầu hết mọi thứ, giả sử bạn đã tạo một dự án (DLL, WinForms, bất cứ thứ gì), bạn chỉ cần sử dụng không gian tên dự án, "Tài nguyên" và mã định danh tài nguyên. ví dụ:
Giả sử một vùng tên dự án: UberSoft.WidgetPro
Và resx của bạn chứa:
Bạn chỉ có thể sử dụng:
Ubersoft.WidgetPro.Properties.Resources.RESPONSE_SEARCH_WILFRED
Hãy thử cái này, phù hợp với tôi .. đơn giản
Giả sử rằng tên tệp tài nguyên của bạn là "TestResource.resx" và bạn muốn chuyển khóa động sau đó,
string resVal = TestResource.ResourceManager.GetString(dynamicKeyVal);
Thêm không gian tên
using System.Resources;
ResourceManager
khi bạn muốn tải một tài nguyên Bên ngoài. Sử dụng <Namespace>.Properties
thay thế.
Mở tệp .resx và đặt "Access Modifier" thành Công khai.
var <Variable Name> = Properties.Resources.<Resource Name>
Giả sử tệp .resx được thêm bằng Visual Studio trong thuộc tính dự án, có một cách dễ dàng hơn và ít bị lỗi hơn để truy cập vào chuỗi.
Sau đó, truy cập chuỗi dễ dàng như sau:
var resourceManager = JoshCodes.Core.Testing.Unit.Properties.Resources.ResourceManager;
var exampleXmlString = resourceManager.GetString("exampleXml");
Thay thế JoshCodes.Core.Testing.Unit
bằng không gian tên mặc định của dự án.
Nếu vì lý do nào đó, bạn không thể đặt tệp tài nguyên của mình vào App_GlobalResources, thì bạn có thể mở tệp tài nguyên trực tiếp bằng ResXResourceReader hoặc Trình đọc XML.
Đây là mã mẫu để sử dụng 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
để sử dụng System.Resources.ResXResourceReader
. Ngoài ra, bạn có thể làm var enumerator = rsxr.OfType<DictionaryEntry>();
và sử dụng LINQ để thay thế.
Khi bạn thêm tài nguyên (Tên: ResourceName và Giá trị: ResourceValue) vào giải pháp / lắp ráp, bạn có thể chỉ cần sử dụng "Properties.Resources.ResourceName" để nhận tài nguyên cần thiết.
Tôi đã thêm tệp .resx qua Visual Studio. Điều này tạo ra một designer.cs
tệp với các thuộc tính để trả về ngay giá trị của bất kỳ khóa nào tôi muốn. Ví dụ: đây là một số mã được tạo tự động từ tệp trình thiết kế.
/// <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);
}
}
Bằng cách đó, tôi có thể đơn giản làm:
string message = Errors.MyErrorMessage;
Ở đâu Errors
là Errors.resx
tập tin được tạo ra thông qua Visual Studio và MyErrorMessage
là chìa khóa.
Tôi đã trực tiếp thêm tệp tài nguyên của mình vào dự án của mình và vì vậy tôi có thể truy cập các chuỗi bên trong chỉ với tên tệp resx.
Ví dụ: trong Resource1.resx, khóa "resourceKey" -> chuỗi "dataString". Để lấy chuỗi "dataString", tôi chỉ cần đặt Resource1.resourceKey.
Có thể có những lý do để không làm điều này mà tôi không biết, nhưng nó đã hiệu quả với tôi.
Cách dễ nhất để làm điều này là:
Cách đơn giản nhất để nhận giá trị từ tệp tài nguyên. Thêm tệp Tài nguyên trong dự án. Bây giờ lấy chuỗi mà bạn muốn thêm vào, giống như trong trường hợp của tôi, đó là khối văn bản (SilverLight). Không cần thêm bất kỳ không gian tên nào. Nó hoạt động tốt trong trường hợp của tôi
txtStatus.Text = Constants.RefractionUpdateMessage;
Tạo trình quản lý tài nguyên để truy xuất tài nguyên.
ResourceManager rm = new ResourceManager("param1",Assembly.GetExecutingAssembly());
String str = rm.GetString("param2");
param1 = "AssemblyName.ResourceFolderName.ResourceFileName"
param2 = tên của chuỗi được truy xuất từ tệp tài nguyên
Điều này làm việc cho tôi. nói rằng bạn có một tệp string.resx với chuỗi ok trong đó. đọc nó
String varOk = My.Resources.strings.ok