Skip to content

Instantly share code, notes, and snippets.

@Seikilos
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Seikilos/a07d9af22181b0262440 to your computer and use it in GitHub Desktop.
Save Seikilos/a07d9af22181b0262440 to your computer and use it in GitHub Desktop.
MSBuild Inline Task to get n newest files from given directory
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask TaskName="GetNewestFiles" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Path ParameterType="System.String" Required="true" />
<FileFilter ParameterType="System.String" Required="true" />
<HowManyFiles ParameterType="System.Int32" Required="true" />
<FilesToCopy ParameterType="System.String[]" Output="true" />
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs"><![CDATA[
DirectoryInfo info = new DirectoryInfo(Path);
FilesToCopy = info.GetFiles(FileFilter)
.OrderByDescending(p => p.CreationTime)
.Select(f =>System.IO.Path.Combine(Path,f.Name)).Take(HowManyFiles).ToArray();
]]></Code>
</Task>
</UsingTask>
<Target Name='Demo' >
<GetNewestFiles Path="d:\temp" FileFilter="*" HowManyFiles="3">
<Output TaskParameter="FilesToCopy" ItemName="FilesToCopy"/>
</GetNewestFiles>
<!-- Copy only these files -->
<Message Text ="Newst Files @(FilesToCopy)" />
<Copy
SourceFiles="@(FilesToCopy)"
DestinationFolder="d:\temp\msbuild\Destination"
/>
<Message Text ="Newest Files as string @(FilesToCopy->'%(filename)%(extension)',' ')" />
</Target>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment