好吧,我们编写了一个自定义任务来按文件名对文件进行排序,然后将要删除的文件列表(不包括列表中的前两个)输出到一个Item
自定义任务:
<UsingTask
TaskName="Cleanup"
TaskFactory="CodeTaskFactory"
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll" >
<ParameterGroup>
<TargetPath ParameterType="System.String" Required="true"/>
<BackupLength ParameterType="System.Int32" Required="true"/>
<FilesToExclude ParameterType="System.String[]" Output="true" />
<FilesToDelete ParameterType="System.String[]" Output="true" />
</ParameterGroup>
<Task>
<Using Namespace="System.IO" />
<Using Namespace="System.Linq" />
<Code Type="Fragment" Language="cs">
<![CDATA[
var diInfo = new DirectoryInfo(TargetPath);
if (diInfo.Exists)
{
var fiInfo = diInfo.GetFiles().OrderByDescending(file => file.Name);
FilesToExclude = fiInfo.Take(BackupLength).Select(file => file.FullName).ToArray();
FilesToDelete = fiInfo.Skip(BackupLength).Select(file => file.FullName).ToArray();
}
]]>
</Code>
</Task>
</UsingTask>
用法:
<!-- Clean old archives. Keep the recent two and deletes rest. -->
<Cleanup TargetPath="$(PackageRoot)" BackupLength="2">
<Output TaskParameter="FilesToDelete" ItemName="FilesToClean" />
</Cleanup>
<Message Text="Cleaning Old Archives" Importance="High" />
<Delete Files="@(FilesToClean)" />