How can I insert lines into a file in an MSBuild T

2020-02-14 21:30发布

问题:

I'm trying to insert some text into a file on the second line of the text. I've currently got it inserting the text at the top by using ReadLinesFromFile. Is there a way to break the list I get back from that into 2 pieces so I can insert on the second line?

What I have now:

<Target>
  <ReadLinesFromFile File="targetfile.txt">
    <Output TaskParameter="Lines" ItemName="TargetFileContents"/>
  </ReadLinesFromFile>

  <WriteLinesToFile File="targetfile.txt" Lines="$(TextToInsert)" Overwrite="true"/>
  <WriteLinesToFile File="targetfile.txt" Lines="@(TargetFileContents)" Overwrite="false"/>
</Target>  

回答1:

It's a bit of a sledge hammer with all the scaffolding, but you can write a task into a project file (or included file, which often has the .targets extension):

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTarget="InsertLine">   
    <Target Name="InsertLine">
        <InsertIntoFile FilePath="test.txt" LineNumber="999" Text="Test complete" />
        <InsertIntoFile FilePath="test.txt" LineNumber="1" Text="2" />
        <InsertIntoFile FilePath="test.txt" LineNumber="2" Text="3" />
        <InsertIntoFile FilePath="test.txt" LineNumber="1" Text="1" />
        <InsertIntoFile FilePath="test.txt" LineNumber="1" Text="Testing the 2MC" />
    </Target>
    <UsingTask
      TaskName="InsertIntoFile"
      TaskFactory="CodeTaskFactory"
      AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >
        <ParameterGroup>
            <FilePath ParameterType="System.String" Required="true" />
            <LineNumber ParameterType="System.Int32"  Required="true" />
            <Text ParameterType="System.String" Required="true" />
        </ParameterGroup>
        <Task>
          <Using Namespace="System" />
          <Using Namespace="System.IO" />
          <Code Type="Fragment" Language="cs">
              <![CDATA[
                // By tradition, text file line numbering is 1-based
                var lines = File.Exists(FilePath) 
                                      ? File.ReadAllLines(FilePath).ToList() 
                                      : new List<String>(1);
                lines.Insert(Math.Min(LineNumber - 1, lines.Count), Text);
                File.WriteAllLines(FilePath, lines);
                return true;
              ]]>
            </Code>
        </Task>
    </UsingTask>
</Project>  


标签: msbuild