Customizing the name of embedded resources in .NET
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.
<Project>
<ItemGroup>
<EmbeddedResource Include="resources\index.html" />
</ItemGroup>
</project>
You can list the embedded resources using the GetManifestResourceNames
method of the Assembly
class.
foreach(var name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
Console.WriteLine(name);
}
You can change the mapping using the LogicalName
attribute.
<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!