如何使用msbuild替换文件中的字符串?

2024-01-06

我想用另一个文件 xy.xml 中的字符串“i am Fine”替换文件 test.xml 中的“how r u”等字符串。在 ms build 中使用正则表达式。

即我必须从一个文件(xy.xml)读取字符串并将其替换为另一个文件test.xml。 因此,请举例说明解决此问题的必要步骤


这不再是必需的...您现在可以将 C# 注入到项目/构建文件中...

定义自定义任务和参数如下:

<UsingTask TaskName="ReplaceFileText" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
  <ParameterGroup>
    <InputFilename ParameterType="System.String" Required="true" />
    <OutputFilename ParameterType="System.String" Required="true" />
    <MatchExpression ParameterType="System.String" Required="true" />
    <ReplacementText ParameterType="System.String" Required="true" />
  </ParameterGroup>
  <Task>
    <Reference Include="System.Core" />
    <Using Namespace="System" />
    <Using Namespace="System.IO" />
    <Using Namespace="System.Text.RegularExpressions" />
    <Code Type="Fragment" Language="cs">
      <![CDATA[
            File.WriteAllText(
                OutputFilename,
                Regex.Replace(File.ReadAllText(InputFilename), MatchExpression, ReplacementText)
                );
          ]]>
    </Code>
  </Task>
</UsingTask>

然后像任何其他 MSBuild 任务一样调用它

<Target Name="AfterBuild">
  <ReplaceFileText 
    InputFilename="$(OutputPath)File.exe.config" 
    OutputFilename="$(OutputPath)File.exe.config" 
    MatchExpression="\$version\$" 
    ReplacementText="1.0.0.2" />
</Target>

上面的示例将输出目录中“File.exe.config”中的“$version$”替换为“1.0.0.2”。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用msbuild替换文件中的字符串? 的相关文章

随机推荐