c# - 如何检测字符串是否在资源文件中
问题描述
如何检测字符串是否包含在 .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
解决方案
这是我在搜索有关如何直接使用 resx 文件的文档时发现的内容:
首先,您可以通过System.Resources.ResXResourceWriter
在System.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
已编辑,但只是为了使具有文本的键的逻辑多元化。
推荐阅读
- r - 为什么将 filter() 放在不同的位置会给出不同的直方图?
- r - 根据列表中数据框的文件名在大列表中设置数据子集
- r - 理解和重建数据帧重载为 d3 格式
- c# - 如何在邮件模板中使用 App.Resources
- android - 如何发送包含字符串数组和文件数组的多部分
- git - 在 Katalon 工作室 GitHub 集成中创建新分支
- python-3.x - 无法使用 beautifulsoup 刮取表格的所有行
- swift - 有没有办法让 @Published 属性实际上得到更新和发布?
- python - Selenium 在无头模式 Ubuntu 18.04 中无法通过 xpath 获取元素
- python - Scrapy - 如何在已启用 cookie 时修复“请启用 cookie”?