How to Exclude some Folders when all Folders are removing in MSBuild?

50 Views Asked by At

i have a MsBuild.targets file which can remove all folder except some folders, in this example we exclude en-us and fa-IR:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="RemoveFolders" AfterTargets="Build">
    <ItemGroup>
      <RemovingFiles Include="$(OutDir)*\*.mui" Exclude="$(OutDir)en-us\*.mui;$(OutDir)fa-IR\*.mui" />
      <RemovingFolders Include="@(RemovingFiles->'%(RootDir)%(Directory)')" />
    </ItemGroup>
    <RemoveDir Directories="@(RemovingFolders)" />
  </Target>
</Project>

now i want to make this codes dynamic with a Property, for example called ExcludedLanguages, so i can exclude every folder i want:

<ExcludedLanguages>en-us;cn-zh</ExcludedLanguages>

but i dont know how to do this? i tried this codes but not working and all folders are removing.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <!-- Comma-separated list of languages to exclude -->
    <ExcludedLanguages>en-US,fa-IR</ExcludedLanguages>
  </PropertyGroup>

  <Target Name="RemoveFolders" AfterTargets="Build">
    <ItemGroup>
      <RemovingFiles Include="$(OutDir)*\*.mui" Exclude="@(ExcludedLanguages->'%(Identity)')\*.mui" />
      <RemovingFolders Include="@(RemovingFiles->'%(RootDir)%(Directory)')" />
    </ItemGroup>
    <RemoveDir Directories="@(RemovingFolders)" />
  </Target>
</Project>
1

There are 1 best solutions below

0
Jonathan Dodds On BEST ANSWER

Going back to your working example, the Exclude is $(OutDir)en-us\*.mui;$(OutDir)fa-IR\*.mui.

Given en-us;cn-zh you want a value for the Exclude of $(OutDir)en-us\*.mui;$(OutDir)cn-zh\*.mui. Put another way, for each excluded language value LANG you want to create a string of the form $(OutDir)LANG\*.mui.

Building from your working example may look like the following:

  <PropertyGroup>
    <!-- Comma-separated list of languages to exclude -->
    <ExcludedLanguages>en-US,fa-IR</ExcludedLanguages>
  </PropertyGroup>

  <ItemGroup>
    <!-- Create an Item collection from the ExcludedLanguages property -->
    <ExcludedLanguage Include="$(ExcludedLanguages.Replace(',', ';'))" />
  <ItemGroup>
  
  <Target Name="RemoveFolders" AfterTargets="Build">
    <PropertyGroup>
      <!-- Use transform on ExcludedLanguage to produce a property -->
      <ExcludeByLanguage>@(ExcludedLanguage->'$(OutDir)%(Identity)\*.mui')<ExcludeByLanguage>
    </PropertyGroup>
    <ItemGroup>
      <!-- Use the generated property to exclude -->
      <RemovingFiles Include="$(OutDir)*\*.mui" Exclude="$(ExcludeByLanguage)" />
      <RemovingFolders Include="@(RemovingFiles->'%(RootDir)%(Directory)')" />
    </ItemGroup>
    <RemoveDir Directories="@(RemovingFolders)" />
  </Target>

(I haven't tested this code. If you find an issue leave a comment and I will address it.)