NAnt script for determining whether an assembly is registered in the GAC


A friend of mine, Kevin Miller, recently put out a public call for anyone who had some NAnt magic for detecting whether a given assembly is in the GAC or not. I had written something like this a year or so ago and I thought I’d share it with everyone in the hopes it might help you.

Standard disclaimer: I don’t guarantee that this works, I don’t guarantee that this won’t explode your computer if you run it. I make no warrantees of any kind.

First, you have to have the .NET SDK installed. If you have Visual Studio 2005 or later, you do. If you’re on a server, make sure you install the .NET Framework 2.0 SDK (free download from MS — SDK x86, SDK x64, and SDK IA64) first.

At the top of your build script somewhere:

<property name="gacutil.exe" value="${framework::get-sdk-directory('net-2.0')}gacutil.exe" />

Next, add the GAC check in a task somewhere (NOTE: Replace the YOUR_ASSEMBLY… with the name of the assembly to find without the “.dll” portion on the end):

<exec program="cmd.exe" failonerror="false" resultproperty="foundInGac" verbose="true"
    commandline="/c gacutil.exe /l YOUR_ASSEMBLY_NAME_WITHOUT_THE_DOT_DLL | %windir%system32find "Number of items = 1"">
    
    <environment>
        <variable name="PATH">
            <path>
                <pathelement path="%PATH%"/>
                <pathelement dir="${framework::get-sdk-directory('net-2.0')}"/>
            </path>
        </variable>
    </environment>
</exec>

In my particular case, I added a task to fail the build if that assembly was in the GAC because it could hose the versioning of my build. Here’s how I did that:

<fail if="${int::parse(foundInGac) == 0}" message="The Core assembly is registered in the GAC. Please un-GAC this assembly before attempting to build the project."/>

</p>

 

I hope this helps someone.

Tying up loose ends