Obtain file sizes in MSBuild script

msbuild

Solution

You can actually use a sub-set of .Net API within msbuild projects using inline tasks.

E.g. the following prints out a file size of a single file:

<UsingTask TaskName="GetFileSize" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
  <ParameterGroup>
    <FileName Required="true" />
    <FileSize ParameterType="System.Int64" Output="true"/>
  </ParameterGroup>
  <Task>
    <Using Namespace="System.IO"/>
    <Code Type="Fragment" Language="cs"><![CDATA[
FileInfo fi = new FileInfo(FileName);
FileSize = fi.Length;
]]></Code>
  </Task>
</UsingTask>

<Target Name="PrintFileSize" >
  <GetFileSize FileName="$(MyFileName)">
    <Output TaskParameter="FileSize" PropertyName="MyFileSize" />
  </GetFileSize>
  <Message Text="file size of $(MyFileName) is $(MyFileSize)" />
</Target>

Problem

Can I find out the sizes of a set of files from an MSBuild script without writing my own code? MSBuild itself some metadata on individual items (for example, the last modified time at %(ModifiedTime) ), but no sizes. I can't see anything at http://msbuildextensionpack.com/. Edit: based on Seva's answer, here's an inline task that returns the total size of an array of items: ``` <UsingTask TaskName="GetFileSize" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll"> <ParameterGroup> <Files ParameterType="Microsoft.Build.Framework.ITaskItem[]" Required="true" /> <TotalSize ParameterType="System.Int64" Output="true"/> </ParameterGroup> <Task> <Using Namespace="System.IO"/> <Code Type="Fragment" Language="cs"><![CDATA[ long l = 0; foreach (var item in Files) { var fi = new FileInfo(item.ItemSpec); l += fi.Length; } TotalSize = l; ]]></Code> </Task> </UsingTask> ```

Original source