我有一个 DLL >> System.Data.SQLite.dll
以正常方式使用它>只需将其添加为引用即可
using System.Data.SQLite;
然后,我就可以使用这个 DLL 中的所有函数了。
但是,我想将我的 app.exe 和这个 DLL 合并到一个文件中。 我曾尝试使用 ILmerge,但失败了。据我所知,ILmerge 无法合并未管理的 DLL。
所以,我尝试了另一种方法 > 将 DLL 制作为嵌入资源。 我可以使用以下代码将其作为程序集加载:
Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyApp.System.Data.SQLite.dll");
byte[] ba = null;
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = stm.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
ba = ms.ToArray();
}
Assembly sSQLiteDLL = Assembly.Load(ba);
但是,我该如何使用 SQLiteDLL 中的函数呢?
我还尝试将 DLL 添加为属性中的资源并像这样加载它:
public Form1()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
InitializeComponent();
}
System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AppDomain domain = (AppDomain)sender;
if (args.Name.Contains("System_Data_SQLite"))
{
return domain.Load(MyApp.Properties.Resources.System_Data_SQLite);
}
return null;
}
以上解释了我到目前为止所了解的内容,但我不知道接下来要做什么才能使用 DLL?我仍然无法使用 DLL 中的函数。
例如,当我键入以下内容时:
SQLiteCommand cmd = new SQLiteCommand();
Visual Studio 说:
错误 21 找不到类型或命名空间名称“SQLiteCommand”(是否缺少 using 指令或程序集引用?)
您能分享一下您的见解吗?谢谢。
最佳答案
您可以嵌入一个程序集并同时引用它(在 VS 中)...对于您想要使用它的方式,您需要引用它!您有什么理由不引用 Assembly 吗?
在不引用的情况下使用嵌入式程序集(托管)中的类型有点困难,但可以使用反射等 - 请参阅这些链接(它们包括引用资料和一些示例代码等):
- http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
- https://stackoverflow.com/a/57450/847363
- http://msdn.microsoft.com/en-us/library/h538bck7.aspx (从字节数组加载一个组合,因此无需将该组合写入文件系统)
- http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettype.aspx
- http://www.codeproject.com/Articles/32828/Using-Reflection-to-load-unreferenced-assemblies-a
在嵌入托管 DLL 时,您有多种选择:
或
- 使用像SmartAssembly这样的工具(商业)
它可以嵌入和合并其他东西(无需更改您的源代码)
或
- code that yourself in less than 10 lines (免费但最小的源代码更改)
将所有需要的依赖项标记为“嵌入式资源”——这样它们就包含在 EXE 文件中……你需要设置一个AssemblyResolve
在运行时从资源中读取并将所需的 DLL 返回给 .NET 运行时的处理程序...
关于c# - 如何使用嵌入资源的 DLL 加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228423/