根据URI检测WPF资源是否存在 [英] Detect whether WPF resource exists, based on URI
问题描述
给定 pack://URI,判断已编译资源(例如,使用资源"的构建操作编译的 PNG 图像)是否实际存在于该 URI 中的最佳方法是什么?
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?
经过一些磕磕绊绊,我想出了这个代码,它有效但很笨拙:
After some stumbling around, I came up with this code, which works but is clumsy:
private static bool CanLoadResource(Uri uri)
{
try
{
Application.GetResourceStream(uri);
return true;
}
catch (IOException)
{
return false;
}
}
(请注意,Application.GetResources 文档错误 -- 如果资源不正确,则会引发异常找到,而不是像文档错误状态那样返回 null.) (文档已更正,请参阅下面的评论)
(Note that the Application.GetResources documentation is wrong -- it throws an exception if the resource isn't found, rather than returning null like the docs incorrectly state.) (The docs have been corrected, see comments below)
我不喜欢捕捉异常来检测预期的(非异常)结果.此外,我实际上并不想加载流,我只想知道它是否存在.
I don't like catching exceptions to detect an expected (non-exceptional) result. And besides, I don't actually want to load the stream, I just want to know whether it exists.
是否有更好的方法来做到这一点,也许使用较低级别的资源 API —— 理想情况下不实际加载流并且不捕获异常?
Is there a better way to do this, perhaps with lower-level resource APIs -- ideally without actually loading the stream and without catching an exception?
推荐答案
我找到了一个我正在使用的解决方案,它不能直接与包 Uri 一起使用,而是通过资源路径查找资源.话虽如此,这个示例可以很容易地修改以支持包 URI,而不是只需将资源路径添加到 uri 的末尾,该 uri 使用程序集来制定 URI 的基本部分.
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<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();
}
}
这篇关于根据URI检测WPF资源是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!