Search code examples
c#.netwpf.net-8.0

ClassLibrary Resources in a .NET 8 project


I want to move my resources, Images and Strings.resx files, from my WPF project to a class library.

So, that a non WPF project could use the same project.

Therefor I created a new class library and move the files to the new project, made sure the Build Action for the images is Resource as it was in the WPF project.

I than noticed that my images aren't included into the *.dll file and the "resource" mechanism doesn't work.

When I do the same BUT with a class library targeting .NET Framework 4.8 and not .NET 8.0 everything works as intended.

I also noticed that when I define <UseWPF>true</UseWPF> in my .NET 8.0 class library it also works as intended.

Sadly the found work arounds don't work for me, since I don't want to target .NET Framework 4.8 and UseWpf would include undesired depencies in a non-wpf project eg. Blazor Project, when I share the class library.

I verified the missing resources with dotPeek here a screenshot, where you can see the difference between the two target frameworks:

enter image description here


Solution

  • Finally got it working...

    With image logo.png in images/logo.png this csproj file should work:

    <Project Sdk="Microsoft.NET.Sdk">
    
        <Import Project="..\targets\Microsoft.WinFX.targets" Sdk="Microsoft.NET.Sdk.WindowsDesktop" />
    
        <PropertyGroup>
            <TargetFrameworks>net8.0</TargetFrameworks>
            <ImplicitUsings>enable</ImplicitUsings>
            <Nullable>enable</Nullable>
        </PropertyGroup>
    
        <ItemGroup>
            <None Remove="Images\Logo.png" />
            <Resource Include="Images\Logo.png" />
        </ItemGroup>
        
    </Project>
    

    the Microsoft.WinFX.targets will allow to compile <Resource /> elements to $(AssemblyName).g.resources in the same way as with UseWPF/UseWindowsForms BUT!!! will not add any references

    The one byte difference, which I was talking in the comments, is that wpf/winforms use System.IO.PinnedBufferMemoryStream and not System.Byte[] to "serialize" image

    Sample project