16

How can I dependably verify the existence of a folder using an msbuild extension pack task?

How could i do it without throwing an error and stopping the build?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Stato Machino
  • 1,120
  • 3
  • 13
  • 22

2 Answers2

37

Could you use the Exists condition on a target?

This will execute the OnlyIfExists target only if there is a directory or file called Testing in the same directory as the msbuild file.

<ItemGroup>
    <TestPath Include="Testing" />
</ItemGroup>
<Target Name="OnlyIfExists" Condition="Exists(@(TestPath))">
    <Message Text="This ran!" Importance="high" />
</Target>
Brian Walker
  • 8,658
  • 2
  • 33
  • 35
13

There is no need to use the extension pack, MSBuild can handle this just fine. You need to consider whether this is a folder that might be created or deleted as part of the build. If it is, then you want to be sure to use a dynamic item group declared within a target (in the case of checking more than one folder) or you can use a path if just checking one. This example shows both:

<Target Name="MyTarget">
   <!-- single folder with property -->
   <PropertyGroup>
      <_CheckOne>./Folder1</_CheckOne>
      <_CheckOneExistsOrNot
          Condition="Exists('$(_CheckOne)')">exists</_CheckOneExistsOrNot>
      <_CheckOneExistsOrNot
          Condition="!Exists('$(_CheckOne)')">doesn't exist</_CheckOneExistsOrNot>
   </PropertyGroup>
   <Message
      Text="The folder $(_CheckOne) $(_CheckOneExistsOrNot)"
      />

   <!-- multiple folders with items -->
   <ItemGroup>
      <_CheckMultiple Include="./Folder2" />
      <_CheckMultiple Include="./Folder3" />
   </ItemGroup>
   <Message
      Condition="Exists('%(_CheckMultiple.Identity)')"
      Text="The folder %(_CheckMultiple.Identity) exists"
      />
   <Message
      Condition="!Exists('%(_CheckMultiple.Identity)')"
      Text="The folder %(_CheckMultiple.Identity) does not exist"
      />
</Target>
Brian Kretzler
  • 9,748
  • 1
  • 31
  • 28