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)
        <EmbeddedResource Include="resources\index.html" />

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

Program.cs (C#)
foreach(var name in Assembly.GetExecutingAssembly().GetManifestResourceNames())

You can change the mapping using the LogicalName attribute.

csproj (MSBuild project file)
    <EmbeddedResource Include="Resources/**/*">

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