c# - 如何使用嵌入资源的 DLL 加载?

标签 c# sqlite resources embed

我有一个 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 吗?

在不引用的情况下使用嵌入式程序集(托管)中的类型有点困难,但可以使用反射等 - 请参阅这些链接(它们包括引用资料和一些示例代码等):

在嵌入托管 DLL 时,您有多种选择:

  • 使用像SmartAssembly这样的工具(商业)
    它可以嵌入和合并其他东西(无需更改您的源代码)

  • code that yourself in less than 10 lines (免费但最小的源代码更改)
    将所有需要的依赖项标记为“嵌入式资源”——这样它们就包含在 EXE 文件中……你需要设置一个 AssemblyResolve在运行时从资源中读取并将所需的 DLL 返回给 .NET 运行时的处理程序...

关于c# - 如何使用嵌入资源的 DLL 加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228423/

相关文章:

ruby-on-rails - 如何处理 xor 条件、rails、外键和 sqlite 数据库?

ruby-on-rails - 找不到 gem 'sqlite3 (>= 0) ruby'

android - 如何检测特定应用程序已启动?

c++ - 是否可以将 dll 添加到资源中,并使用 LoadLibrary 从资源中加载该 dll? C++

c# - 每个版本的资源

c# - 如何将在代码隐藏中创建的图表添加到呈现的 html 页面?

c# - ID一次性接口(interface)

c# - 微软Unity注册

ios - 是否可以将 NSMutableArray 存储在 NSObject 中?

c# - SSL API 请求截至今天失败 : "Could not create SSL/TLS secure channel"