Creating a list of Folders in an ItemGroup using MSBuild

北战南征 提交于 2019-12-17 22:56:57

问题


I'm trying to build an ItemGroup in an MSBuild script which contains a list of folders directly below a given 'Root' folder. So - in this example...

+ Root folder
---- Sub Folder 1
-------- Sub-Sub Folder 1
-------- Sub-Sub Folder 2
---- Sub Folder 2
---- Sub Folder 3

... I would want my ItemGroup to contain "Sub Folder 1", "Sub Folder 2" and "Sub Folder 3".

There may be a number of files at any point in the hierarchy, but I'm only interested in the folders.

Can anyone help!?


回答1:


<PropertyGroup>
    <RootFolder>tmp</RootFolder>
</PropertyGroup>
<ItemGroup>
   <AllFiles Include="$(RootFolder)\**\*"/>
   <OnlyDirs Include="@(AllFiles->'%(Directory)')"/>
</ItemGroup>

@(OnlyDirs) might contain duplicates, so you could either use the RemoveDuplicatesTask :

<Target Name="foo">
   <RemoveDuplicates Inputs="@(OnlyDirs)">
      <Output TaskParameter="Filtered" ItemName="UniqueDirs"/>
   </RemoveDuplicates>
</Target>

or use CreateItem with batching for %(AllFiles.Identity) or with msbuild 3.5:

<Target Name="foo">
   <ItemGroup>
      <UniqueDirs Include="%(AllFiles.Directory)"/>
   </ItemGroup>
</Target>



回答2:


In MSBuild 4.0 this is possible:

<ItemGroup>
  <Folders Include="$([System.IO.Directory]::GetDirectories(&quot;$(RootFolder)&quot;))" />
</ItemGroup>

Property Functions: http://msdn.microsoft.com/en-us/library/dd633440.aspx




回答3:


The MSBuild Extension pack has a task called FindUnder, which returns an itemgroup of files or folders below a certain path. The following task will achieve what you want, returning an itemgroup containing Sub Folder 1, Sub Folder 2, and Sub Folder 3, but not Sub-Sub Folder 1 or Sub-Sub Folder 2:

<MSBuild.ExtensionPack.FileSystem.FindUnder
    TaskAction="FindDirectories"
    Path="$(RootFolder)"
    Recursive="False">
    <Output ItemName="FoundFolders" TaskParameter="FoundItems" />
</MSBuild.ExtensionPack.FileSystem.FindUnder>



回答4:


MSBuild 4.0:

<PropertyGroup>
     <RootFolder>tmp</RootFolder>
</PropertyGroup>
<ItemGroup>
    <AllFiles Include="$(RootFolder)\**\*"/>
    <OnlyDirs Include="@(AllFiles->'%(RootDir)%(Directory)'->Distinct())"/>
</ItemGroup>



回答5:


This MSDN Forum post has a custom task that deals with the empty directory case (upvoted accepted as its a v useful answer)



来源:https://stackoverflow.com/questions/1657684/creating-a-list-of-folders-in-an-itemgroup-using-msbuild

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!