Is there a way to configure a nuGet package so that a file is installed, inside a project, only if it does not already exist in the project?

Specifically, my nuGet package contains a custom config file. Once installed, the user will make modifications to the file. The problem is that the config file gets replaced when the user installs a new version of my nuGet package -- thus, losing their changes. I want to prevent this.

2

There are 2 answers

1
J W On BEST ANSWER

Let's assume that you are using Visual Studio and need to deploy log4net.config if it is missing.

  • Create the "tools" folder under the folder with your *.nuspec file
  • Add to the nuspec file:

         <file src="tools/**/*.*" target="\" /> 
      </files>
    </package>
    

It will include the files in the tools folder into the package

  • place inside the tools folder the file install.ps1 with some code similar to:

    param($installPath, $toolsPath, $package, $project)
    
    $log4netInProjectFolder = $project.ProjectItems | Where-Object { $_.Properties.Item("Filename").Value -eq "log4net.config" }
    
    if ($log4netInProjectFolder -eq $null)
    {
        Write-Host "File with path $deployTarget doesn't exist, deploying default log4net.config"
    
        foreach($item in $filesToMove) 
        {
            Write-Host "Moving " $item.Properties.Item("FullPath").Value
            (Get-Interface $project.ProjectItems "EnvDTE.ProjectItems").AddFromFileCopy($item.Properties.Item("FullPath").Value)
            (Get-Interface $item "EnvDTE.ProjectItem").Delete()
        }   
     }
     else
    {
        Write-Host "File $deployTarget already exists, preserving existing file."
    }
    

Create the package using (for example):

nuget pack PackageWithMyLogConfig.nuspec -Version 1.0.0

If you want to look inside the generated package, rename it to *.zip. Then you can view what's inside using any archive manager.

0
Lerrand On

Probably an old question but here it goes anyway, as I also had this problem:

This can be done by manually updating the packages using the command line as shown in the PowerShell reference:

Update-Package [-Id] <string> [-IgnoreDependencies] [-ProjectName <string>] [-Version <string>] [-Source <string>] [-Safe] [-IncludePrerelease] [-Reinstall] [-FileConflictAction] [-WhatIf]    

The parameter you need to use is -FileConflictAction which you must set to Ignore.

Edit: Problem is, this does not work for only one specific file, so you may have to consider renaming the config file included in the package.