EDIT 5/11/2013: This question originally asked how to programmatically register a COM object using code from .NET without having to use REGASM. Yahia's answer covers both how to register a DLL programmatically and an EXE.
ORIGINAL QUESTION: At the moment, we have a batch script that we call from our UI to register/unregister our software in COM when setting the default version (using regasm and adding registry entries). We no longer wish to use a batch script as we are running into a problem where if the script fails, the program is not aware of the failure. There are several ways I can address the issue, but I don't like the notion of calling batch scripts from code if I don't have to, so I'd like to switch to registering our software with COM using managed code.
Assuming it's possible, how do you register/unregister COM objects from C#? Googling only turns up ways to do this from installer packages, or tells me to use regasm, but I can't find any information on how to do this programmatically or if it's even possible.
Thanks in advance for any assistance with this.
EDIT 5/10/2013: It looks like registering an EXE as a COM object is not the same as registering a DLL. Is there a programmatic way in .NET (PInvoke is fine) to register an EXE as a COM object (in the 32 bit registry)? This is currently how we're doing it in the script, the app and REGCMD vars are just shorthand:
set app=%PathToTheExecutable%
set REGCMD=%PathTo32BitRegExe%
"C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm" /tlb /codebase %app%
%REGCMD% ADD HKCR\CLSID\{app-guid}\LocalServer32 /ve /t REG_SZ /d %app% /f
%REGCMD% DELETE HKCR\CLSID\{app-guid}\InprocServer32 /f
Basically we run regasm on the executable, then add our exe as a LocalServer32 and remove the entry which associates us as an InprocServer. Is it possible to do this programmatically without having to call regasm from code?
You can do that in C# - but only by using some pinvoke, specifically LoadLibrary / GetProcAddress / FreeLibrary.
Basically you need to load the DLL, call the register/unregister functions inside that DLL and then unload it.
For a complete walkthrough including working C# source code see here. Reference see MSDN as per comment.
UPDATE after the OP updated the question:
The above method only works for DLLs.
With Assemblies (esp. EXE COM-server implemented in .NET) the easiest and most robust option is actually to use regasm
.
IF you really need to do this programmatically you should take a look at these MSDN-links:
Basically you need to load your EXE via Assembly.Load
and then call RegisterTypeForComClients
on the relevant Type
s.
Another option is to do this dynamically (at runtime) - perhaps this is of some use to you...