Search code examples
c#nuget

How to read text from an included content file in a nuget package


I have a html file included in my nuget package. But how can i then reference and read from that file in the nuget project?


What i tried so far

placed .html file in a contentFiles dir in the project.

enter image description here

included it in the nuget package.

enter image description here

contentFiles here contains the .html file.

enter image description here

Now i want to be able to read the contents of that html file from inside my nuget package.

Here is some example code that does not work.

        var path = Assembly.GetExecutingAssembly().Location.Replace("Ssff.dll", "Inlined.html");
        var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        var textPath = Path.Combine(assemblyDirectory, "contentFiles", "Inlined.html");
        
        // File.ReadAllText(path) and File.ReadAllText(textPath); does not work

Once this nuget package is consumed and tries to runs this code, it cannot find the html file. So the previous code if not uncommented just throws a file not found exception. So this whole thing boils down to how do i find that html file included in my nuget package.

This is what it looks like in the project consuming the nuget package. Note that there isnt a .html file or a contentFiles folder.

enter image description here

the PackageReference looks like this

<PackageReference Include="Ssff" Version="0.9.4.4">
    <IncludeAssets>all</IncludeAssets>
</PackageReference>

Solution

  • In the .csproj for the package library, change <CopyToOutput>true</CopyToOutput> to <PackageCopyToOutput>true</PackageCopyToOutput> for the desired Content files.

    Per documentation on NuGet packing via MSBuild:

    Other pack specific metadata that you can set on any of the above items includes <PackageCopyToOutput> and <PackageFlatten> which sets CopyToOutput and Flatten values on the contentFiles entry in the output nuspec.

    Translation: <PackageCopyToOutput> will tell consumers of this NuGet package to copy the desired Content files to their output, whereas <CopyToOutput> is not 'passed through' to the consuming projects.