5

I use a third-party nuget package that contains a content file that appears in my project which I'd like to copy to my output folder. Said and done.

Unfortunately what the project file then does is this:

<Content Update="C:\Users\djdoe\.nuget\packages\thirdpartynuget\1.0.2\contentFiles\any\net472\thefile.txt">
  <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

I tried

<Content Update="%userprofile%\.nuget

but then it won't copy the file. Is there a way to configure the reference with a $ variable that Visual Studio will understand?

Edit: Thanks to Marnix I found two variables pointing to the nuget folder:

$(NuGetPackageFolders)

$(NuGetPackageRoot)

Both of them work for me

2
  • 1
    Would this list help you out? stackoverflow.com/questions/830271/… Commented Sep 15, 2023 at 6:52
  • 1
    @Marnix Actually it does. There seem to be two of them $(NuGetPackageFolders) and $(NuGetPackageRoot) both of which work for me. Thanks Commented Sep 15, 2023 at 7:10

1 Answer 1

11

What you probably want is a feature in NuGet called GeneratePathProperty. It lets you opt into generating MSBuild Properties you can use for your own scripts.

Do note however that the source NuGet package could also specify that the file is supposed to be copied to the output directory. See this blog post for an explanation.

To use the generated MSBuild property, you can do the following:

<Project>
  ...
  <ItemGroup>
    <!-- specify GeneratePathProperty on the package reference -->
    <PackageReference Include="Third.Party.Package"
      Version="1.0.2"
      GeneratePathProperty="True" />
  </ItemGroup>

  <ItemGroup>
    <!-- Use the generated property ("Pkg" + msbuild-friendly package name) -->
    <Content Update="$(PkgThird_Party_Package)\contentFiles\any\net472\thefile.txt"
      CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>
</Project>
Sign up to request clarification or add additional context in comments.

1 Comment

This GeneratePathProperty attribute technique is absolute gold and if you are reading this, then you better be upvoting this answer right now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.