Как получить имя по строке Значение из файла ресурсов .NET(RESX)
Вот как выглядит мой файл RESX:
Name Value Comments
Rule_seconds seconds seconds
Rule_Sound Sound Sound
Я хочу:
Имя по строке Значение, что-то вроде ниже:
public string GetResxNameByValue(string value)
{
// some code to get name value
}
И реализуйте его, как показано ниже:
string str = GetResxNameByValue("seconds");
чтобы str
вернул Rule_seconds
Спасибо!
Ответы
Ответ 1
Это может работать
private string GetResxNameByValue(string value)
{
System.Resources.ResourceManager rm = new System.Resources.ResourceManager("YourNamespace.YourResxFileName", this.GetType().Assembly);
var entry=
rm.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(e => e.Value.ToString() ==value);
var key = entry.Key.ToString();
return key;
}
С дополнительной проверкой ошибок.
Ответ 2
вы можете получить доступ непосредственно, пройдя ключ:
public string gtresource(string rulename)
{
string value = null;
System.Resources.ResourceManager RM = new System.Resources.ResourceManager("CodedUITestProject1.Resource1", this.GetType().Assembly);
value = RM.GetString(rulename).ToString();
if(value !=null && value !="")
{
return value;
}
else
{
return "";
}
}
Ответ 3
На всякий случай это может помочь кому угодно. Этот ResourceHelper вдохновлен jure и Моханом Сингхом Саини.
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Threading;
public class ResourceHelper
{
/// <summary>
/// ResourceHelper
/// </summary>
/// <param name="resourceName">i.e. "Namespace.ResourceFileName"</param>
/// <param name="assembly">i.e. GetType().Assembly if working on the local assembly</param>
public ResourceHelper(string resourceName, Assembly assembly)
{
ResourceManager = new ResourceManager(resourceName, assembly);
}
private ResourceManager ResourceManager { get; set; }
public string GetResourceName(string value)
{
DictionaryEntry entry = ResourceManager.GetResourceSet(Thread.CurrentThread.CurrentCulture, true, true).OfType<DictionaryEntry>().FirstOrDefault(dictionaryEntry => dictionaryEntry.Value.ToString() == value);
return entry.Key.ToString();
}
public string GetResourceValue(string name)
{
string value = ResourceManager.GetString(name);
return !string.IsNullOrEmpty(value) ? value : null;
}
}
Ответ 4
public static class ResourceManagerHelper
{
public static string GetResourceName(this ResourceManager resourceManager, string value, CultureInfo cultureInfo, bool ignoreCase = false)
{
var comparisonType = ignoreCase ? System.StringComparison.OrdinalIgnoreCase : System.StringComparison.Ordinal;
var entry = resourceManager.GetResourceSet(cultureInfo, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(dictionaryEntry => dictionaryEntry.Value.ToString().Equals(value, comparisonType));
if (entry.Key == null)
throw new System.Exception("Key and value not found in the resource file");
return entry.Key.ToString();
}
}
Чтобы вызвать этот метод расширения,
var key = Resources.ResourceManager.GetResourceName(value, CultureInfo.InvariantCulture, true);
В этом случае мы не хотим передавать сборку ресурсов, вместо этого мы можем использовать конкретный ресурс resourceManager.
Ответ 5
Вы можете использовать этот встроенный код (С#, ASP.NET MVC)
var _resource = new ResourceManager(typeof(/*your resource*/));
string res = _resource.GetString(/*resource key*/);
Я думаю, что это могло бы помочь u.