Customizing the name of embedded resources in .NET

 
 
  • Gérald Barré

When you use embedded resources in a .NET project, the resource name is computed from the path of the file. By default, it uses a format similar to <Assembly Name>.<File Path>. But the file path doesn't contain a path separator (/ or \). Instead, the path separator is replaced by a dot (.). For example, the resource name for the file resources/index.html is MyAwesomeProject.resources.index.html. So, if you want to create a virtual file system from the embedded resources, you may not be sure which embedded resources you need to read as they can be conflicts.

csproj (MSBuild project file)
<Project>
    <ItemGroup>
        <EmbeddedResource Include="resources\index.html" />
    </ItemGroup>
</project>

You can list the embedded resources using the GetManifestResourceNames method of the Assembly class.

Program.cs (C#)
foreach(var name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
    Console.WriteLine(name);
}

You can change the mapping using the LogicalName attribute.

csproj (MSBuild project file)
<Project>
  <ItemGroup>
    <EmbeddedResource Include="Resources/**/*">
      <LogicalName>$([System.String]::new('%(RelativeDir)').Replace('\','/'))%(FileName)%(Extension)</LogicalName>
    </EmbeddedResource>
  </ItemGroup>
</Project>

If you run the previous code, the resource names should be different:

Using this mapping, it's much easier to create a virtual file system from the embedded resources as the file names correspond to the actual file hierarchy.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub