Home > OS >  How do you register COM assemblies programmatically in C#?
How do you register COM assemblies programmatically in C#?

Time:08-09

I guess technically, it doesn't have to be a COM assembly specifically. But, I wanted to include that because that's how I searched for it myself.

Currently, we use a batch file that registers them with the following line:

c:\windows\microsoft.net\framework\v4.0.30319\regasm.exe c:\Path\To\AssemblyToRegister.dll /codebase /s /tlb

How would you register it in C# code so we can get rid of the batch files and automate this process a little better?

CodePudding user response:

Note: The following code requires the application to be run as administrator!

Assembly asm = Assembly.LoadFrom(@"c:\Path\To\AssemblyToRegister.dll");
RegistrationServices regAsm = new RegistrationServices();
bool bResult = regAsm.RegisterAssembly(asm, AssemblyRegistrationFlags.SetCodeBase);

I found this answer originally from this page. However, we ran into an issue where it threw an exception on the third line with a certain dll and found that the "LoadFile" form line 1 should have been "LoadFrom". Here is the link to the Stack Overflow question where we found the fix.

CodePudding user response:

Here is my first attempt which is not the best way of doing this. I am adding in-case it helps someone in the future.

This code assumes an absolute path to the dll is provided in the dllLocation variable. You might also have to change the regasm location value to wherever it's installed on your machine.

string regasmLocation = @"c:\windows\microsoft.net\framework\v4.0.30319\regasm.exe";
try
{
   Process p = new Process();
   p.StartInfo.UseShellExecute = false;
   p.StartInfo.RedirectStandardError = true;
   p.StartInfo.RedirectStandardOutput = true;
   p.StartInfo.FileName = regasmLocation;
   // If you want the tlb (type library) created use the following.
   //p.StartInfo.Arguments = dllLocation   @" /codebase /s /tlb";
   p.StartInfo.Arguments = dllLocation   @" /codebase /s";
   p.Start();

   // To avoid deadlocks, always read the output stream first and then wait. https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standarderror?view=net-6.0
   string standardError = p.StandardError.ReadToEnd();
   string standardOutput = p.StandardOutput.ReadToEnd();
   p.WaitForExit();

   Console.WriteLine($"Successfully registered '{dllLocation}'.");
   if (!string.IsNullOrWhiteSpace(standardOutput))
   {
      Console.WriteLine($"Standard Output: \n{standardOutput}");
   }

   if (!string.IsNullOrWhiteSpace(standardError))
   {
      Console.WriteLine($"Standard Error: \n{standardError}");
   }
}
catch (Exception ex)
{
   Console.WriteLine(ex);
   return false;
}
return true;

This is limited because it runs regasm through a console window. This means that you can't really handle exceptions. I would suggest doing it programmatically with my other answer.

  • Related