.NET for Android error APT2264

Issue

The tool aapt2 is unable to resolve one of the files it was passed. This is generally caused by the path being longer than the Maximum Path length allowed on windows.

Solution

The best way to avoid this is to ensure that your project is not located deep in the folder structure. For example if you create all of your projects in folders such as

C:\Users\shelly\Visual Studio 2022\Android\MyProjects\Com.SomeReallyLongCompanyName.MyBrillantApplication\MyBrilliantApplicaiton.Android\

you may well encounter problems with not only aapt2 but also Ahead of Time compilation. Keeping your project names and folder structures short, concise will help work around these issues. For example instead of the above you could use

C:\Work\Android\MyBrilliantApp

Which is much shorter and much less likely to encounter path issues.

However this is not always possible. Sometimes a project or a environment requires deep folder structures. Enabling long path support in Windows might be enough to get your project working. Details on how to do this can be found here.

If long path support does not work changing the location of the $(BaseIntermediateOutputPath) can help solve these problems. In order for this to work the setting MUST be changed before ANY build or restore occurs. To do this you can make use of the MSBuild Directory.Build.props support.

Creating a Directory.Build.props file in your solution or project directory which redefines the $(BaseIntermediateOutputPath) to somewhere nearer the root of the drive with solve these issues. Adding a file with the following contents will create the obj directory in a different location of your choosing.

<Project>
  <PropertyGroup>
      <BaseIntermediateOutputPath Condition=" '$(OS)' == 'Windows_NT' ">C:\Intermediate\$(ProjectName)</BaseIntermediateOutputPath>
      <BaseIntermediateOutputPath Condition=" '$(OS)' != 'Windows_NT' ">/tmp/Intermediate/$(ProjectName)</BaseIntermediateOutputPath>
  </PropertyGroup>
</Project>

Using this technique will reduce the lengths of the paths sent to the various tools like aapt2. Note this is generally only a Windows issue. So there is no need to override the $(BaseIntermediateOutputPath) on Mac or Linux based environments. However you might want to override everywhere to be consistent.