back to Jitbit Blog home About this blog

Nuget Authoring: copying content files into you project folder

by Alex Yumashev · Updated Jul 4 2021

I'm a nuget package author and all I wanted to do is to include a .cs file into project's root folder. And I want it to work both with the old packages.config and the new PackageReference mechanisms.

The issue I was having is that the new PackageReference mode was not copying files from the <contentFiles> to my project folder when installing the nuget package.

After hours of googling, here's how you write a .nuspec file to include a file into project's folder, so it's supported by both "old" and "new" nuget.

  <metadata>
    ...
    <contentFiles>
      <files include="**/myfile.cs" flatten="true" />
    </contentFiles>
  </metadata>
  <files>
      <file src="myfile.cs" target="contentFiles\any\any" /> <!-- this is for new format -->
      <file src="myfile.cs" target="content" /> <!-- this is for the old format -->
  </files>

Explanation: in the new nuget model, the <files> node is for the packer, the <contentFiles> node is for the consumer of the package. The former instructs nuget how to pack the files, the latter tells the consumer what to do with the extracted files. In our nuget package above we're telling the packer to put our file into contentFiles folder.

Mind the weird any/any subfolder - it's a naming convention that tells nuget to use this file with any language and any target framework. And in the <contentFiles> element we tell the consumer to extract those files when installing. The double wildcard simply says "look in any subfolder(s)", to skip the "any/any" for readability.

But this "any/any" thing will fail to install in older projects, that use packages.config mode! That is why we're also duplicating the file in content fodler that is recognized by the old nuget system.