NuGet可以编辑配置文件还是只添加它?

Dar*_*rcy 17 nuget nuget-package

我一直在为我公司制作一个NuGet包,其中一个要求是能够更新我们的一些配置文件.

我知道可以添加到配置文件,但是可以编辑一个吗?

例:

<add name="conn" connectionString="Data Source=.\;Initial Catalog=DB;Integrated Security=True" />
Run Code Online (Sandbox Code Playgroud)

改为以下

<add name="conn" connectionString="Data Source=.\;Initial Catalog=DB;User ID=ex;Password=example" />
Run Code Online (Sandbox Code Playgroud)

Lee*_*old 30

NuGet变换无法编辑现有值.但NuGet允许您在程序包安装上运行Powershell脚本,因此您可以通过这种方式编辑配置文件.

创建Install.ps1文件并使用以下代码:

# 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)
Run Code Online (Sandbox Code Playgroud)


Eri*_*oen 15

从NuGet 2.6及更高版本开始,您可以使用在Visual Studio中用于Web.config转换的XDT语法实际转换Web.config文件.

请参阅http://docs.nuget.org/docs/creating-packages/configuration-file-and-source-code-transformations:

支持XML文档转换(XDT)

从NuGet 2.6开始,支持XDT转换项目中的XML文件.XDT语法可以在包的Content文件夹下的.install.xdt和.uninstall.xdt文件中使用,该文件将分别在包安装和卸载时应用.

例如,要将MyNuModule添加到web.config文件中,如上所示,可以在web.config.install.xdt文件中使用以下部分:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer>
        <modules>
            <add name="MyNuModule" type="Sample.MyNuModule" xdt:Transform="Insert" />
        </modules>
    </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

另一方面,要在程序包卸载期间仅删除MyNuModule元素,可以在web.config.uninstall.xdt文件中使用以下部分:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <system.webServer>
        <modules>
            <add name="MyNuModule" xdt:Transform="Remove" xdt:Locator="Match(name)" />
        </modules>
    </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

  • 这不是原始问题的实际目标吗?将ti应用于消费项目? (2认同)