简体   繁体   English

从C#Windows窗体项目文件夹中加载DLL

[英]Loading DLLs from a folder, C# windows form project

Well i've seen this being done in another project, which was also using windows forms, and i'm just curious on how it can be done. 好吧,我已经看到这是在另一个使用Windows窗体的项目中完成的,我只是很好奇它的完成方式。 Basically what i'm asking for example: I have 2 windows form projects, currently there both separate but i'd like to incorporate them into each-other. 基本上是我要问的一个例子:我有2个Windows窗体项目,目前这两个项目是分开的,但是我想将它们相互合并。 One big aspect of this will be how to load the 2nd project into the 1st. 其中一个重要方面是如何将第二个项目加载到第一个项目中。 So i've built my seconded project as a .dll file. 因此,我已经将借调的项目构建为.dll文件。 And i then want to place that .dll file into a folder inside the project and then be able search for any .dlls in the folder and load them up. 然后,我想将该.dll文件放入项目内的文件夹中,然后能够在该文件夹中搜索任何.dll并加载它们。

So i know i can do this via adding the .dll file from my 2nd project into the references of the first project, but specifically im wondering if it can be done without this? 所以我知道我可以通过将第二个项目中的.dll文件添加到第一个项目的引用中来执行此操作,但是我特别想知道如果没有此操作是否可以完成? So that in my first project i can just say; 这样,在我的第一个项目中,我可以说: "Search "DirectoryName", if there's any .dll files in that folder, load them up, and add them to a list in the project that the user ie me can see & hopefully use." “搜索“ DirectoryName”,如果该文件夹中有任何.dll文件,请加载它们,然后将它们添加到项目中的列表中,以便我(即我)用户看到并希望使用。

What you're looking for can be achieved by using a mechanism called Reflection 您正在寻找的东西可以通过使用称为反射的机制来实现

Reflection allows you to dynamically load an assembly into your application, among other things. 通过反射,您可以将程序集动态加载到应用程序中。

The class you'd need is called Assembly that has several useful methods for loading assemblies: 您需要的类称为Assembly ,它具有几种用于加载程序集的有用方法:

LoadFile, LoadFrom and a few more. LoadFile,LoadFrom等。

Here's a code example of loading an assembly at a given path : 这是在给定路径下加载程序集的代码示例:

string path = @"D:\Folder\MyDll.dll";
Assembly assembly = Assembly.LoadFrom(path);

Once you have loaded an assembly and have a reference to an Assembly object, you can create objects that are defined in it, invoke their methods and so on. 一旦加载了程序集并引用了Assembly对象,就可以创建在其中定义的对象,调用其方法等。

More resources can be found here: Dynamically loading and using Types 在这里可以找到更多资源: 动态加载和使用类型

You may be interested in using the Managed Entity Framework to achieve this. 您可能对使用托管实体框架实现此目标感兴趣。

Alternatively, you can use Assembly.LoadFrom(), as described here . 或者,您可以使用Assembly.LoadFrom(),如此处所述

Here are some useful links. 这里是一些有用的链接。

Asked on SO: here and here External blog example 在SO上提问: 这里这里外部博客示例

Basically you will need to load the library, enumerate the types and use Activator.CreateInstance() to create a new object. 基本上,您将需要加载库,枚举类型并使用Activator.CreateInstance()创建新对象。 Having interfaces for the classes you need to interact with will help you here too 为您需要与之交互的类提供接口也将为您提供帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM