Load a com DLL in c#

0

I want to load a COM dll dynamically in c# console application.

Till now I have tried the following code:

// load exe with args as EXE DllName classNameTobeLoaded
try
{
 // load assembly
 Assembly Dll = Assembly.LoadFile(@"C:\My_Dir\TestComDll.dll");
 // get the type names
 foreach(Type t in Dll.GetExportedTypes())
 {
   dynamic vClassLoaded = Activator.CreateInstance(t,"Test");
   Console.WriteLine("Type Loaded");
 }

  Console.WriteLine("DLL is loaded");
}
catch (Exception ex)
{
  Console.WriteLine("Unable to load a DLL because \n" + ex.Message);
}

But while loading the dll I am getting error as:

{System.BadImageFormatException: The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
   at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
   at System.Reflection.Assembly.LoadFile(String path)
   at ThirdPartyDLLLoader.Program.Main(String[] args) in h:\Test Exe\ThirdPartyDLLLoader\ThirdPartyDLLLoader\Program.cs:line 18}

The same code is working fine for .NET DLL.

Can any one tell me why the code is not able to load a COM dll dynamically?

and if it is not can you please tell me how I can do the same.

Thanks for any suggestion and help.

c#
.net
dll
com
asked on Stack Overflow Oct 12, 2015 by A B

2 Answers

0

This cannot be done. The Assembly.LoadFrom method is for loading .NET assemblies. COM library must be registered and then you can instantiate classes using Activator.CreateInstance method.

This is how I access MS Word:

Type type = Type.GetTypeFromProgID("Word.Application");
object obj = Activator.CreateInstance(type);
answered on Stack Overflow Oct 12, 2015 by Nytmo • edited Oct 12, 2015 by Nytmo
-1

I have a function load a class library dll

 public ICollection<Assembly> GetAssemblies(string pathOfDLL)
    {
        List<Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
        var controllersAssembly = Assembly.LoadFrom(pathOfDLL);
        baseAssemblies.Add(controllersAssembly);
        return baseAssemblies;
    }

Hope it helps!

answered on Stack Overflow Oct 12, 2015 by Lewis Hai

User contributions licensed under CC BY-SA 3.0