您可以Stream
使用 获取 DLL Assembly.GetManifestResourceStream
,但是为了对其进行任何操作,您需要将其加载到内存中并调用Assembly.Load
,或者将其提取到文件系统(然后很可能仍然调用Assembly.Load
or 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