Load a COM dll at runtime?

≡放荡痞女 提交于 2019-12-04 07:35:35

Late-binding to COM objects requires that you do NOT add a reference to the COM library to your .NET project. Instead, you should you use something like this to create COM objects:

   Type type = Type.GetTypeFromProgID("Excel.Application")
   object app = Activator.CreateInstance(type);

Then, it will bind to any version of the COM library at runtime.

See this article for more details.

Yoenhofen

This is the solution

Compile a version agnostic DLL in .NET

In case that link ever dies, the key is to handle the AppDomain.CurrentDomain.AssemblyResolve event like below. The event fires any time an assembly binding fails, so you can resolve it yourself, fixing version conflicts.

using System.Reflection;

static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
    {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "Office11Wrapper")
        {
            // Put code here to load whatever version of the assembly you actually have

            return Assembly.LoadFile("Office11Wrapper.DLL");
        }
        else
        {
            return null;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!