How to find the current file in MSBuild

msbuild

I know that the latest book out on MSBuild says this is not possible, but I am sure I have seen a property that points to the current file.

Does anyone know a way to find the current file? (ie When the main MSBuild file imports a secondary file. What is the path to the secondary file from inside that file.)

I am trying to register my file in HKEY_LOCALMACHINE\Software\Microsoft\VisualStudio\8.0\MSBuild\SafeImports, but the path to the file is not constant on each of my coworkers computers and it is imported from several different projects so doing a hard coded relative path is not a good idea either.

If there is a way to get the current working directory that will work too (the working directory switches with each import and I think I could save it off)

Best Answer

There is not a reliable means to identify the "current file". When MSBuild processes a file it can import several other files, the end result is a single in memory complete representation of the file. When the targets are executing they do not know which file they were declared in.

This is why reusable build scripts must be "parameterized" to accept the location to known relative locations. For example if you have a dependency on the location where your folder for 3rd party references are located, the build script which is driving the process must declare that property for you.

MSBuild 4.0 Only

If you are using MSBuild 4.0, i.e. Visual Studio 2010/.NET 4.0, (which can target .NET 2.0/3.0/3.5) as well. Then you now have these properties which can be used for this specific purpose:

  • MSBuildThisFile
  • MSBuildThisFileDirectory
  • MSBuildThisFileDirectoryNoRoot

Sayed Ibrahim Hashimi

My Book: Inside the Microsoft Build Engine : Using MSBuild and Team Foundation Build

Related Topic