Can NuGet edit a config file or only add to it?

后端 未结 4 1898
时光取名叫无心
时光取名叫无心 2020-12-14 02:57

I\'ve been working on a NuGet package for my company and one of the requirements is being able to update some of our config files.

I know it\'s possible to add to a

4条回答
  •  再見小時候
    2020-12-14 03:31

    NuGet transforms can't edit existing values. But NuGet lets you run Powershell scripts on package install, so you can edit the config file that way.

    Create an Install.ps1 file and use this code:

    # Install.ps1
    param($installPath, $toolsPath, $package, $project)
    
    $xml = New-Object xml
    
    # find the Web.config file
    $config = $project.ProjectItems | where {$_.Name -eq "Web.config"}
    
    # find its path on the file system
    $localPath = $config.Properties | where {$_.Name -eq "LocalPath"}
    
    # load Web.config as XML
    $xml.Load($localPath.Value)
    
    # select the node
    $node = $xml.SelectSingleNode("configuration/connectionStrings/add[@name='gveconn']")
    
    # change the connectionString value
    $node.SetAttribute("connectionString", "Data Source=.\;Initial Catalog=GVE;User ID=ex;Password=example")
    
    # save the Web.config file
    $xml.Save($localPath.Value)
    

提交回复
热议问题