开发者

How do I check if a COM dll is registered in C#

开发者 https://www.devze.com 2023-01-06 11:11 出处:网络
I created a Office Add-In in VS 2008, C#, .NET 3.5, and VSTO. It is deployed via ClickOnce. A run-time configuration form executes regsvr32 to register \"fooapi.dll\" included with the project that ca

I created a Office Add-In in VS 2008, C#, .NET 3.5, and VSTO. It is deployed via ClickOnce. A run-time configuration form executes regsvr32 to register "fooapi.dll" included with the project that can not be registered during instal du开发者_Python百科e to ClickOnce limitations. Is there any prefered way to check and see if "fooapi.dll" is registered during run-time in C#?


Try the Type.GetTypeFromCLSID or Type.GetTypeFromProgID methods to quickly check for a COM interface's existence.

Alternatively, just instantiate the object and trap the exception, e.g.

catch(COMException ex) {
    if(ex.ErrorCode == -2147221164) {
        // Retrieving the COM class factory for component with CLSID XXXX failed
    }
}

UPDATE:

This overload appears to be the only one that actually returns null if the COM object cannot be instantiated.


If you know the DLLs GUID, you could check the existance of the registry key in HKCU\SOFTWARE\Classes.


Check the presence of HKEY_CLASSES_ROOT\CLSID\{your_CLSID} and the proper values under it. You could probably get away with looking for InprocServer32 and Codebase values only, but you might also opt-in for more extensive check.

You can also just create an instance of the component. However, if both the component and the client are C# and you use new, the CLR might be able to figure out the proper assembly and load it with going through COM. (Yes, it can be smart like that sometimes :-)). You should explicitly p/invoke to CoCreateInstance


If you have the progID of the component in the DLL, you can try getting the Type:

System.Type.GetTypeFromProgID(string progID, bool throwOnError)

If you get System.Runtime.InteropServices.COMException, it means that the progID is not registered.


I think the simplest way is to try and create the component which lives in fooapi.dll. Wrap the creation code in a try/catch block and catch the exception which is generated if the DLL is not properly registered. This is the surest way to check for correct registration

0

精彩评论

暂无评论...
验证码 换一张
取 消