Monday, January 7, 2008

Registering Assembly to GAC via Code

Registering Assembly to GAC via Code

As we know to register an assembly toGlobal Assembly Cache, the assembly must be strong named. This strong name is used to prevent spoofing of your code. Use the “gacutil.exe” to install the assembly to the GAC.


Example


gacutil /i MyAssembly.dll


The above command will installs the “MyAssembly.dll” in to the GAC.
See the following code snippet to do the above stuff by C# code.

try
{
string assemblyName = “MyAssembly.dll”;

ProcessStartInfo pStartInfo = new ProcessStartInfo();

//specify gacutil.exe whith which to start the process
pStartInfo.FileName = "gacutil.exe";
pStartInfo.Arguments = string.Format("/i {0}", assemblyName);
pStartInfo.UseShellExecute = false;

//start the process
Process process = Process.Start(pStartInfo);

//wait till the process completes
process.WaitForExit();
}
catch (Exception e)
{
MessageBox.Show(string.Format
("Error registering the assembly :
'{0}'.\n{1}"
, assemblyName, e.Message),
"GAC Installation Error");
}


The “UseShellExecute” property indicates whether to use the operating system shell to start the process. The default is “true”. Set this property to “false” – The process is created directly from the executable file.

No comments: