I currently use GetManifestResourceStream to access embedded resources. The name of the resource comes from an external source that is not case sensitive. Is there any way to access embedded resources in a case insensitive way?
I would rather not have to name all my embedded resources with only lower case letters.
Assuming that you know the resource names from the external source and are only lacking the capitalization, this function creates a dictionary you can use for lookups to align the two sets of names.
you know -> externally provided
MyBitmap -> MYBITMAP
myText -> MYTEXT
/// <summary>
/// Get a mapping of known resource names to embedded resource names regardless of capitlalization
/// </summary>
/// <param name="knownResourceNames">Array of known resource names</param>
/// <returns>Dictionary mapping known resource names [key] to embedded resource names [value]</returns>
private Dictionary<string, string> GetEmbeddedResourceMapping(string[] knownResourceNames)
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
string[] resources = assembly.GetManifestResourceNames();
Dictionary<string, string> resourceMap = new Dictionary<string, string>();
foreach (string resource in resources)
{
foreach (string knownResourceName in knownResourceNames)
{
if (resource.ToLower().Equals(knownResourceName.ToLower()))
{
resourceMap.Add(knownResourceName, resource);
break; // out of the inner foreach
}
}
}
return resourceMap;
}
If you don't want to create a dictionary upfront then this will work.
private static Stream GetResourceStream(string name)
{
var assembly = Assembly.GetExecutingAssembly();
// Replace path separators with '.' separators
var path = string
.Concat( assembly.GetName().Name, ".", name)
.Replace('/','.')
.Replace('\\','.');
// Match using case invariant matching
path = assembly
.GetManifestResourceNames()
.FirstOrDefault(p => p.ToLowerInvariant() == path.ToLowerInvariant());
if(path==null)
throw new ArgumentNullException($"Can't find resource {name}",nameof(name));
var manifestResourceStream = assembly.GetManifestResourceStream(path);
if (manifestResourceStream == null)
throw new ArgumentNullException($"Can't find resource {name}",nameof(name));
return manifestResourceStream;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With