首页 > 解决方案 > 如何检测字符串是否在资源文件中

问题描述

如何检测字符串是否包含在 .resx 文件中?

我知道我可以在 .resx 文件中创建所有字符串的列表,然后使用Contains函数来查看我的字符串是否是其中的一部分,但是有没有更简单的方法?我在上述 .resx 文件中有很多字符串,将来还会添加更多字符串,因此似乎需要大量维护。

var text = "hello";
var resourceList = new List<string> 
{
    // All my resource strings
    CharacterEntities.word1, // "hello"
    CharacterEntities.word2, // "to"
    CharacterEntities.word3, // "Stack"
    CharacterEntities.word4  // "Overflow"
}

var isContained = resources.Contains(text);

编辑

我需要检查一个字符串是否包含特定字符串(所有特定字符串都在 中CharacterEntities)。

我想避免创建resourceList列表并直接使用我的资源文件CharacterEntities.resx

标签: c#string

解决方案


这是我在搜索有关如何直接使用 resx 文件的文档时发现的内容:

首先,您可以通过System.Resources.ResXResourceWriterSystem.Windows.Forms程序集中组成一个:

var resxPath = @"some\path\here.resx";

using (var resx = new ResXResourceWriter(resxPath)) {
    resx.AddResource("res1", "A resource");
    resx.AddResource("res2", "Another resource");
    resx.AddResource("res3", "Yet another resource");
}       

如果您使用“文本”的目的是查找 resx 文件中是否存在密钥,那么您可以使用ResXResourceReader

var key = "res2";
var keyExists = false;

using (var resx = new ResXResourceReader(resxPath)) 
    foreach(DictionaryEntry entry in resx)
        if(entry.Key.ToString() == key)
            keyExists = true;

Console.WriteLine(keyExists); // True

如果您的意图是找出哪些键有您的文本,您可以这样做:

var text = "other";
var keysHavingText = new List<string>();

using (var resx = new ResXResourceReader(resxPath)) 
    foreach(DictionaryEntry entry in resx)
        if(entry.Value.ToString().Contains(text))
            keysHavingText.Add(entry.Key.ToString());

Console.WriteLine(string.Join(",",keysHavingText)); // res2,res3

当然,要回答您关于文本是否在 resx 文件中的问题,您只需查看变量是否有任何条目:

var isContained = keysHavingText.Count > 0; 
Console.WriteLine(isContained); // True

已编辑,但只是为了使具有文本的键的逻辑多元化。


推荐阅读