Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace string in file using msbuild?

I want to replace a string such "how r u" in file test.xml with a string "i am fine" in another file xy.xml.using regular expression in ms build.

ie i have to read string from one file(xy.xml) and replace it in another file test.xml. so please provide necessary steps to solve this issue with example

like image 615
Nithin Avatar asked Oct 20 '11 14:10

Nithin


2 Answers

This is no longer required... you can now inject C# into the project/build file...

Define a custom task and parameters as follows:

<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> 

Then simply call it like any other MSBuild task

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

The above example replaces "$version$" with "1.0.0.2" in the "File.exe.config" located in the output directory.

like image 87
csharptest.net Avatar answered Sep 22 '22 13:09

csharptest.net


There is very simple approach to just replace string in a file:

  <Target Name="Replace" AfterTargets="CoreCompile">       <PropertyGroup>           <InputFile>c:\input.txt</InputFile>           <OutputFile>c:\output.txt</OutputFile>       </PropertyGroup>       <WriteLinesToFile           File="$(OutputFile)"           Lines="$([System.IO.File]::ReadAllText($(InputFile)).Replace('from','to'))"           Overwrite="true"           Encoding="Unicode"/>   </Target> 

See https://docs.microsoft.com/en-us/visualstudio/msbuild/property-functions?view=vs-2019 to explore inlinable C# code. [System.Text.RegularExpressions.Regex] included into the list.

like image 30
Dmitriy Ivanov Avatar answered Sep 21 '22 13:09

Dmitriy Ivanov