簡體   English   中英

在C#中加載com DLL

[英]Load a com DLL in c#

我想在c#控制台應用程序中動態加載COM dll。

到目前為止,我已經嘗試了以下代碼:

// 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);
}

但是在加載dll時出現以下錯誤:

{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}

相同的代碼對於.NET DLL正常工作。

誰能告訴我為什么代碼不能動態加載COM dll?

如果不是,請告訴我我該怎么做。

感謝您的任何建議和幫助。

我有一個函數加載類庫dll

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

希望能幫助到你!

無法做到這一點。 Assembly.LoadFrom方法用於加載.NET程序集。 必須注冊COM庫,然后才能使用Activator.CreateInstance方法實例化類。

這是我訪問MS Word的方式:

Type type = Type.GetTypeFromProgID("Word.Application");
object obj = Activator.CreateInstance(type);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM