Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 config file, but is it possible to edit one?

Example:

<add name="conn" connectionString="Data Source=.\;Initial Catalog=DB;Integrated Security=True" />

changes to below

<add name="conn" connectionString="Data Source=.\;Initial Catalog=DB;User ID=ex;Password=example" />
like image 688
Darcy Avatar asked Aug 01 '11 17:08

Darcy


1 Answers

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)
like image 132
Lee Harold Avatar answered Sep 28 '22 07:09

Lee Harold