Is there a way to tell nuGet to install a file, into a project, only if the file is not already in the project?

你离开我真会死。 提交于 2019-12-01 21:17:06

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26917278/is-there-a-way-to-tell-nuget-to-install-a-file-into-a-project-only-if-the-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!