开发者

WPF - check resource exists without structured exception handling

开发者 https://www.devze.com 2023-02-05 11:41 出处:网络
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开发者

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

精彩评论

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