Install Assembly in GAC with C#

9. April 2008 05:42 by Mrojas in General  //  Tags: , , , ,   //   Comments (0)

 

Do you want to create a program to install your assembly in the GAC using C#. Well if you had that requirement or you are just curious, here is how.

I read these three articles:

Demystifying the .NET Global Assembly Cache

GAC API Interface 

Undocumented Fusion

What I wanted just a straight answer of how to do it. Well here is how:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.GAC;
//// Artinsoft
//// Author: Mauricio Rojas orellabac@gmail.com mrojas@artinsoft.com
//// This program uses the undocumented GAC API to perform a simple install of an assembly in the GAC
namespace AddAssemblyToGAC
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an FUSION_INSTALL_REFERENCE struct and fill it with data
            FUSION_INSTALL_REFERENCE[] installReference = new FUSION_INSTALL_REFERENCE[1];
            installReference[0].dwFlags = 0;
            // Using opaque scheme here
            installReference[0].guidScheme = System.GAC.AssemblyCache.FUSION_REFCOUNT_OPAQUE_STRING_GUID;
            installReference[0].szIdentifier = "My Pretty Aplication Identifier";
            installReference[0].szNonCannonicalData= "My other info";
 
            // Get an IAssemblyCache interface
 
            IAssemblyCache pCache = AssemblyCache.CreateAssemblyCache();
            String AssemblyFilePath = args[0];
 
            if (!System.IO.File.Exists(AssemblyFilePath))
            {
                Console.WriteLine("Hey! Please use a valid path to an assembly, assembly was not found!");
            }
            int result = pCache.InstallAssembly(0, AssemblyFilePath,installReference);
            //NOTE recently someone reported a problem with this code and I tried this:
            // int result = pCache.InstallAssembly(0, AssemblyFilePath,null); and it worked. I think is a marshalling issue I will probably review it later
 
            Console.WriteLine("Process returned " + result);
            Console.WriteLine("Done!");
 
        }
 
    }
}

And here's the complete source code for this application: DOWNLOAD SOURCE CODE AND BINARIES