Kev*_*vin 3 c# dll resources embedded-resource
有没有关于如何在 ac# 源代码中使用资源嵌入 dll 的详细指南?我在谷歌上找到的所有指南似乎都没有多大帮助。都是“创建一个新类”或“ILMerge”这个和“.NETZ”那个。但我不确定如何使用 ILMerge 和 .NETZ 的东西,并且类指南遗漏了创建类文件后要做什么,因为这样做后我没有发现任何新内容。例如,这个. 添加类和函数后,我不知道如何从我的资源中获取 dll。
因此,具体来说,我正在寻找的是有关如何使用能够调用 a 的.dll
文件的指南,而无需省略部分。请记住,我对 C# 编码不太有经验。提前致谢。:Dembedded into Resources
class
附言。尽量不要使用那些大词。我很容易迷路。
您可以使用Stream
来获取 DLL Assembly.GetManifestResourceStream
,但是为了用它做任何事情,您需要将其加载到内存中并调用Assembly.Load
,或者将其提取到文件系统(然后很可能仍然调用Assembly.Load
或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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
构建代码:
> csc /target:library DemoLib.cs
> csc DemoExe.cs /resource:DemoLib.dll
Run Code Online (Sandbox Code Playgroud)