开发者

WPF - check resource exists without structured exception handling

Is there any way to check if a resource exists in an assembly without having to use exception handling? I'm currently loading images from several assemblies, and if they don't exist then I'm ha开发者_StackOverflow社区ndling the IOException, which causes quite a bit of overhead.


Would something like this work for you?

// Member Variable
string [] resourceNames;

// Function
Boolean ResourceExists(string resourceName)
{
    if (resourceNames == null)
    {
        resourceNames =  
            Assembly.GetExecutingAssembly().GetManifestResourceNames(); 
    }

    return resourceNames.Contains(resourceName);
}


Copied answer from here:

public static bool ResourceExists(string resourcePath)
{
    var assembly = Assembly.GetExecutingAssembly();

    return ResourceExists(assembly, resourcePath);
}

public static bool ResourceExists(Assembly assembly, string resourcePath)
{
    return GetResourcePaths(assembly)
        .Contains(resourcePath);
}

public static IEnumerable<object> GetResourcePaths(Assembly assembly)
{
    var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
    var resourceName = assembly.GetName().Name + ".g";
    var resourceManager = new ResourceManager(resourceName, assembly);

    try
    {
        var resourceSet = resourceManager.GetResourceSet(culture, true, true);

        foreach(System.Collections.DictionaryEntry resource in resourceSet)
        {
            yield return resource.Key;
        }
    }
    finally
    {
        resourceManager.ReleaseAllResources();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜