Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve embedded resource using case insensitive filename in .Net

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.

like image 630
Darrel Miller Avatar asked Dec 04 '22 15:12

Darrel Miller


2 Answers

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;
}
like image 171
Mark Avatar answered Apr 29 '23 19:04

Mark


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;
}
like image 30
bradgonesurfing Avatar answered Apr 29 '23 19:04

bradgonesurfing