如何在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屋!
查看全文