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 handling the IOException, which causes quite a bit of overhead.
Asked
Active
Viewed 6,074 times
5
-
This is the only working solution IMHO: https://stackoverflow.com/questions/2013481/detect-whether-wpf-resource-exists-based-on-uri – Jason Stevenson Apr 28 '22 at 23:15
2 Answers
7
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);
}

Wonko the Sane
- 10,623
- 8
- 67
- 92
-
2Thanks, we've ended up using a similar approach where we build a dictionary of resources contained in an assembly, then this dictionary is checked against when retrieving an image. – devdigital Jan 18 '11 at 14:39
0
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();
}
}

TarmoPikaro
- 4,723
- 2
- 50
- 62