Warm tip: This article is reproduced from serverfault.com, please click

Include File in NuGet package on Build, only if it does not exist

发布于 2020-12-02 10:32:53

A while ago I asked this question:

Including a Folder in NuGet Package and have it install into project as file .netcore/Razor

The answer to which has got me most of the way where I want to go, but the trouble is rebuilding or updating the NuGet package in my projects is now overwriting files that are user-editable.

I feel the answer is somewhere in the .props file but I am not sure how to achieve it:

<Project>
  <Target Name="CopyFiles" BeforeTargets="Build" >
   <ItemGroup>
      <File  Include="$(MSBuildThisFileDirectory)..\Pagesettings\*.*"></File>
   </ItemGroup>
    <Copy SourceFiles="@(File)" DestinationFolder="$(ProjectDir)Pagesettings"></Copy>
  </Target>
</Project>

The Target tag has an optional attribute Condition. I am guessing that somehow this can be used...?

So, to clarify my question:

From my original question linked above I have a NuGet package which when downloaded creates a folder called PageSettings, into which is copied a bunch of default JSON files containing PageSettings from my NuGet package. NOTE; these files initially appear in Visual Studio as linked files. They are not actually copied to the directory until the project is built.

However, the purpose of these PageSettings files is to be a default , or if you like an example, of PageSettings for users of my NuGet package. Once installed, the user can and should change these .JSON files, so now when their project is rebuilt, or if there is an update to the NuGet package available which they install, these JSON files should NOT update/install.

Questioner
Jamie Hartnoll
Viewed
11
Perry Qian-MSFT 2020-12-03 10:57:03

Sure. My answer quite has some flaws. To prevent overwriting existing files and files that have changed, I suggest you use xcopy with /d. It will not overwrite the existing files.

Instead, use this in test.props file:

<Project>
  <Target Name="CopyFiles" BeforeTargets="Build">
    <ItemGroup>     
      <File Include="$(MSBuildThisFileDirectory)..\Pagesettings\*.*"></File>          
    </ItemGroup>
      <Exec Command="xcopy /s/d/y @(File) $(ProjectDir)Pagesettings\"></Exec>
      
      
      <!--<Copy SourceFiles="@(File)" DestinationFolder="$(PorojectDir)Pagesettings" Condition="!Exists('$(PorojectDir)Pagesettings\*.*')"></Copy>-->
  </Target>
</Project>

Then, repack your nuget project. Before using this new one, please clean nuget caches first.