Detect whether WPF resource exists, based on URI

前端 未结 1 1770
囚心锁ツ
囚心锁ツ 2021-02-07 16:18

Given a pack:// URI, what\'s the best way to tell whether a compiled resource (e.g. a PNG image, compiled with a Build Action of \"Resource\") actually exists at that URI?

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 17:06

    I've found a solution that I'm using which doesn't work directly with a pack Uri but instead looks up a resource by it's resource path. That being said, this example could be modified pretty easily to support a pack URI instead by just tacking on the resource path to the end of a uri which uses the Assembly to formulate the base part of the URI.

    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.ToLowerInvariant());
    }
    
    public static IEnumerable 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 讨论(0)
    提交回复
    热议问题