如何加载2个嵌入式dll?

时间:2013-12-05 08:20:44

标签: c#

我有两个dll(xNet.dllag.dll),我想在我的项目中使用它。

我将它们添加到资源中,表示构建操作是嵌入式资源。 接下来我有这样的代码来加载第一个dll:

public Form1()
{
    AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
    InitializeComponent();
}

private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
    Assembly assembly = Assembly.GetExecutingAssembly();

    string assemblyName = args.Name.Split(',')[0];

    using (Stream stream = assembly.GetManifestResourceStream("Yandex.dll.xNet.dll"))
    {
        if (stream == null)
            return null;

        byte[] rawAssembly = new byte[stream.Length];
        stream.Read(rawAssembly, 0, (int)stream.Length);
        return Assembly.Load(rawAssembly);
    }
}

如何加载第二个dll?

2 个答案:

答案 0 :(得分:0)

您应匹配请求的程序集名称并返回正确的程序集。

我不知道你的程序集名称,所以我只做一个非常简单的匹配,但它应该看起来像:

private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
    if (args.Name.Contains("xNet"))
    {
        return LoadAssemblyFromResource("Yandex.dll.xNet.dll");
    } 

    if (args.Name.Contains("ag"))
    {
        return LoadAssemblyFromResource("ag.dll");
    }

    return null;
}

private static Assembly LoadAssemblyFromResource(string resourceName)
{
    Assembly assembly = Assembly.GetExecutingAssembly();

    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    {
        if (stream == null)
            return null;

        byte[] rawAssembly = new byte[stream.Length];
        stream.Read(rawAssembly, 0, (int)stream.Length);
        return Assembly.Load(rawAssembly);
    }
}

答案 1 :(得分:0)

为什么不将dll提取到临时路径然后加载它们。假设你有两个dll,即 firstDll secondDll ,两者都将构建操作设置为Resource

然后将这些dll提取到临时路径,就像这样;

byte[] firstAssembly=Properties.Resources.firstDll;
File.WriteAllBytes(@"C:\Temp\firstDll.dll",firstAssembly);

byte[] secondAssembly=Properties.Resources.secondDll;
File.WriteAllBytes(@"C:\Temp\secondDll.dll",secondAssembly);

在此之后使用Reflection来加载这些组件并使用它们。

相关问题