e82.eric
e82.eric

Reputation: 313

Move AfterBuild target to a .targets file

I have a AfterBuild target that I would like to use for multiple projects in a solution. Is there a way that I can put that target into a .targets file and reference the file in each project.

Below is what I tried which does not seem to work.

Project File:

<Import Project="..\debug.targets"/>

.Targets File:

    <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="AfterBuild">
    <PropertyGroup>
        <WebsiteDirectory>C:\Inetpub\wwwroot</WebsiteDirectory>
    </PropertyGroup>

    <ItemGroup>
        <output Include=".\**\*.dll" Exclude=".\**\obj\**" />
        <output Include=".\**\*.pdb" Exclude=".\**\obj\**" />
        <output Include=".\**\*.svc" />
        <output Include=".\**\*.xap" />
        <output Include=".\**\*.aspx" />
        <output Include=".\**\*.js" />
        <output Include=".\**\*.config" />
    </ItemGroup>

    <PropertyGroup>
        <VirtualDirectoryPath>$(WebsiteDirectory)\$(RootNamespace)</VirtualDirectoryPath>
    </PropertyGroup>

    <copy SourceFiles="@(output)" DestinationFiles="@(output->'$(VirtualDirectoryPath)\%(RecursiveDir)%(Filename)%(Extension)')" />
</Target>

Upvotes: 4

Views: 1785

Answers (2)

Matt Slagle
Matt Slagle

Reputation: 1085

Use this

<Import Project="$(MSBuildThisFileDirectory)\debug.targets"/> 

$(MSBuildThisFile) = The current project file.
$(MSBuildThisFileDirectory) = The directory that contains current project file.

Relative paths in project files are difficult to use depending on what is invoking the project file. Using msbuild directly and the relative path will resolve to the project file. Use VS and the relative path will use the solution file as the base path.

Using $(MSBuildThisFileDirectory) will force the relative path to use a pre-determined beginning path. All you need to do is fill in the rest of the relative path.

Upvotes: 4

Ritch Melton
Ritch Melton

Reputation: 11598

What you are doing is fundamentally correct, but ensure that your Import statement is the last Import in the project file.

To verify that the target is being invoked correctly, run msbuild in diag mode from the command line and note the output regarding your target.

msbuild myproj.proj /v:diag

Upvotes: 1

Related Questions