确定ResourceManager中是否存在资源

时间:2020-03-06 15:00:03  来源:igfitidea点击:

无论如何,有没有确定ResourceManager是否包含命名资源?当前,我正在捕获MissingManifestResourceException,但我讨厌在非异常情况下必须使用Exception。必须有某种方法可以通过反射来枚举ResourceManager的名称/值对,或者其他方式?

编辑:更多细节。资源不在执行程序集中,但是ResourceManager运行正常。如果我尝试_resourceMan.GetResourceSet(_defaultCuture,false,true),则为null,而如果我尝试_resourceMan.GetString(" StringExists"),则返回字符串。

解决方案

我认为我们可以使用Assembly.GetManifestResourceNames之类的名称来枚举Assembly清单中可用的资源列表。它不是很漂亮,不能解决所有极端情况,但是可以根据需要运行。

我们可以使用ResourceSet来做到这一点,只有在枚举时,它才会将所有数据加载到内存中。在这里:

// At startup.
    ResourceManager mgr = Resources.ResourceManager;
    List<string> keys = new List<string>();

    ResourceSet set = mgr.GetResourceSet(CultureInfo.CurrentCulture, true, true);
    foreach (DictionaryEntry o in set)
    {
        keys.Add((string)o.Key);
    }
    mgr.ReleaseAllResources();

    Console.WriteLine(Resources.A);