3

是否有关于如何在 ac# 源中使用资源嵌入 dll 的详细指南?我在 Google 上找到的所有指南似乎都没有多大帮助。这都是“创建一个新课程”或“ILMerge”这个和“.NETZ”那个。但是我不确定如何使用 ILMerge 和 .NETZ 的东西,并且类的指南忽略了制作类文件后要做什么,因为这样做后我没有发现任何新东西。例如,. 添加类和函数后,我不知道如何从我的资源中获取 dll。

所以,具体来说,我正在寻找的是关于如何使用能够调用 a的.dll文件的指南,没有和部分遗漏。请记住,我对 C# 编码不是很有经验。提前致谢。:Dembedded into Resourcesclass

PS。尽量不要使用那些大词。我很容易迷路。

4

2 回答 2

4

您可以Stream使用 获取 DLL Assembly.GetManifestResourceStream,但是为了对其进行任何操作,您需要将其加载到内存中并调用Assembly.Load,或者将其提取到文件系统(然后很可能仍然调用Assembly.Loador Assembly.LoadFile,除非您已经实际上已经依赖它了)。

加载程序集后,您必须使用反射来创建类的实例或调用方法等。所有这些都非常繁琐-特别是我永远记不起调用Assembly.Load(或类似方法)的各种重载的情况. Jeff Richter 的“CLR via C#”一书将是您办公桌上的有用资源。

你能否提供更多关于你为什么需要这样做的信息?我已经将清单资源用于各种事情,但从不包含代码......有什么理由你不能将它与你的可执行文件一起发布吗?

这是一个完整的示例,尽管没有错误检查:

// DemoLib.cs - we'll build this into a DLL and embed it
using System;

namespace DemoLib
{   
    public class Demo
    {
        private readonly string name;

        public Demo(string name)
        {
            this.name = name;
        }

        public void SayHello()
        {
            Console.WriteLine("Hello, my name is {0}", name);
        }
    }
}

// DemoExe.cs - we'll build this as the executable
using System;
using System.Reflection;
using System.IO;

public class DemoExe
{
    static void Main()
    {
        byte[] data;
        using (Stream stream = typeof(DemoExe).Assembly
               .GetManifestResourceStream("DemoLib.dll"))
        {
            data = ReadFully(stream);
        }

        // Load the assembly
        Assembly asm = Assembly.Load(data);

        // Find the type within the assembly
        Type type = asm.GetType("DemoLib.Demo");

        // Find and invoke the relevant constructor
        ConstructorInfo ctor = type.GetConstructor(new Type[]{typeof(string)});
        object instance = ctor.Invoke(new object[] { "Jon" });

        // Find and invoke the relevant method
        MethodInfo method = type.GetMethod("SayHello");
        method.Invoke(instance, null);
    }

    static byte[] ReadFully(Stream stream)
    {
        byte[] buffer = new byte[8192];
        using (MemoryStream ms = new MemoryStream())
        {
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, bytesRead);
            }
            return ms.ToArray();
        }
    }
}

构建代码:

> csc /target:library DemoLib.cs
> csc DemoExe.cs /resource:DemoLib.dll
于 2009-12-08T07:03:06.990 回答
2

您可能需要使用 ILMerge。看起来它会自然地为您解决问题。

http://research.microsoft.com/en-us/people/mbarnett/ILMerge.aspx

于 2009-12-08T07:10:01.513 回答