How to only add a file if it doesn't already exist using Nuget and the nuspec file
I have been suffering for this issue since yesterday. At first, I have the same idea as the accepted answer in the link provided in your question, using install.ps1
in the Tools
folder with function that if a example.css
file already exists, nuget update will not overwrite it. So I tried to create this install.ps1
, but I failed.
That because:
- The file
install.ps1
runs after the package is installed in a
project.
- Update package will uninstall the old version package including contents.
Detailed for the reasons 1:
According to the document Run PowerShell script during NuGetpackage installation and removal:
Install.ps1
runs when a package is installed in a project.
We could get the hidden information, file Install.ps1
runs after package installed.
In order to verify it, I have created a test sample nuget package with .nuspec
:
<?xml version="1.0"?>
<package >
<metadata>
<id>MyTestPackage</id>
<version>1.0.0</version>
<authors>Tester</authors>
<owners>Tester</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Package description</description>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<copyright>Copyright 2018</copyright>
<tags>Tag1 Tag2</tags>
</metadata>
<files>
<file src="bin\Debug\MyTestPackage.dll" target="lib\net462" />
<file src="css\example.css" target="content\css\example.css" />
<file src="Tools\install.ps1" target="Tools\install.ps1" />
</files>
</package>
And the content of install.ps1
:
Start-Sleep -Seconds 20
write-host "Hello world!"
Start-Sleep -Seconds 5
Then I added my MyTestPackage.nupkg
to the test project, I found that the content added to the project before install.ps1
was executed.
Then I created a version 2.0.0 with different content in the example.css
file (Just for testing), then I updated the package from 1.0.0 to 2.0.0, the example.css
wil be replaced before install.ps1
was executed:

When we update the nuget package, nuget will update the package and overwrite contents first, then executed the file install.ps1
. So it seems we could not use the file install.ps1
to prevent NuGet overwrite the file example.css
file.
Detailed for the reasons 2:
If you pay attention to the upgrade process in the animation above, you will find that when upgrading the package, nuget will remove the package including contents first, then re-install the new version package. So, nuget will remove the package and its content first when we update the package, the result of the conditional judgment file existence is always negative. NuGet will add the .css file in the new version nuget package to the project.
If you have to prevent nuget overwrite this/those file(s), As workaround for this issue, you can include this/those file(s) in a new nuget package, this/those file(s) will not be overwritten in the new nuget package when you upgrade your original package.
Hope this helps.