C# 使用msbuild更改连接字符串
我正在尝试在Teamcity服务器上使用MSBUILD更改web.config中的connectionString。之前,我在一个目标中使用了该属性,该目标称为:C# 使用msbuild更改连接字符串,c#,msbuild,C#,Msbuild,我正在尝试在Teamcity服务器上使用MSBUILD更改web.config中的connectionString。之前,我在一个目标中使用了该属性,该目标称为: <PropertyGroup> <UpdateWebConfigCode> <![CDATA[ public static void ScriptMain() { XmlDocument wcXml = new XmlDocument(); wcXml.Load(@"TCM.MVC.
<PropertyGroup>
<UpdateWebConfigCode>
<![CDATA[
public static void ScriptMain()
{
XmlDocument wcXml = new XmlDocument();
wcXml.Load(@"TCM.MVC.UI\Web.config");
XmlElement root = wcXml.DocumentElement;
XmlNodeList connList = root.SelectNodes("//connectionStrings/add");
XmlElement elem;
foreach (XmlNode node in connList)
{
elem = (XmlElement)node;
switch (elem.GetAttribute("name"))
{
case "TCMBaseConnectionString":
elem.SetAttribute("connectionString", "Data Source=server-name;Initial Catalog=TCMCentral;User ID=user;Password=something");
break;
}
}
wcXml.Save(@"TCM.MVC.UI\Web.config");
}
]]>
</UpdateWebConfigCode>
然后,我会将其称为目标:
<Target Name="UpdateWebConfig">
<Script Language="C#" Code="$(UpdateWebConfigCode)" Imports="System.Xml" />
</Target>
但这不断抛出一个错误。我意识到这可能有点过时,但找不到任何东西来取代它。。。。有什么建议吗?我使用一个自定义任务来执行此操作,该任务与您的代码基本相同,但MSBuidl变为:
<UpdateConnectionString ConfigFile ="path\to\web.config"
ConnectionStringName="MyConnectionStringName"
ConnectionString="connection-string-here"/>
请注意,如果连接字符串不存在,此代码还将添加一个连接字符串,这可能比您现在需要的更复杂。我最后使用了MSBuildCommunityTasks XmlUpdate属性。以下是我的目标:
<Target Name="UpdateWebConfig">
<XmlUpdate XmlFileName="C:\TCM.NET\Current\TCM.MVC.UI\web.config" XPath="configuration/connectionStrings/add[@name='TCMBaseConnectionString']/@connectionString" Value="Data Source=server-name;Initial Catalog=TCMCentral;User ID=user;Password=something" />
</Target>
这对我很有用。杰米,谢谢你的帮助。我最终在MSBuildCommunityTasks中使用了XmlUpdate属性。见下面我的答案。再次感谢。作为一个不错的选择,我也开始改用更通用的“UpdateXml”类型的任务,尽管这是我自己的创作任务,而不是MSBuildCommunity。
<Target Name="UpdateWebConfig">
<XmlUpdate XmlFileName="C:\TCM.NET\Current\TCM.MVC.UI\web.config" XPath="configuration/connectionStrings/add[@name='TCMBaseConnectionString']/@connectionString" Value="Data Source=server-name;Initial Catalog=TCMCentral;User ID=user;Password=something" />
</Target>