如何在 MSBuild 任务中将行插入文件? [英] How can I insert lines into a file in an MSBuild Task?
本文介绍了如何在 MSBuild 任务中将行插入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一些文本插入到文本第二行的文件中.我目前使用 ReadLinesFromFile
在顶部插入文本.有没有办法将我从那里得到的列表分成两部分,以便我可以在第二行插入?
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?
我现在拥有的:
<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>
推荐答案
这有点像大锤,所有的脚手架,但你可以将任务写入项目文件(或包含文件,通常具有 .targets扩展名):
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 任务中将行插入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文