在项目中“作为链接添加”时如何引用dll?
作者:互联网
我在项目树中有两个dll文件(不是引用).它们被添加为链接,它们是解决方案中其他项目的组件.我正在尝试将其“构建操作”设置为“嵌入式资源”,因此可以将其导入到.exe文件.我无法使用using语句编写,因此无法在当前项目中引用它们.那怎么办?
project file http://img593.imageshack.us/img593/7048/dll.png
解决方法:
您需要添加对程序集的硬引用,并将其“本地复制”设置为False,然后在调用程序集之前将程序集从嵌入式资源中提取到应用程序目录中.您无法随意引用链接(快捷方式).
关键点(在此示例中)和Blog Article with Example Code
> EmbeddedReferenceApplication硬引用EmbeddedReference.dll
> EmbeddedReference参考属性Copy Local设置为False
>将链接的装配体(添加为链接)设置为嵌入式资源
这是一个工作示例. (EmbeddedReferenceApplication.exe |控制台应用程序)
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Reflection;
using EmbeddedReference; // Hard reference with Copy Local = False
namespace EmbeddedReferenceApplication {
class Program {
static void Main(string[] args) {
AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve;
MyMain();
}
private static void MyMain() {
EmbeddedReference.MessageHelper.ShowMessage();
}
private static Assembly AppDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
string manifestResourceName = "EmbeddedReferenceApplication.EmbeddedReference.dll"; // You can also do Assembly.GetExecutingAssembly().GetManifestResourceNames();
string path = Path.Combine(Application.StartupPath, manifestResourceName.Replace("EmbeddedReferenceApplication.", ""));
ExtractEmbeddedAssembly(manifestResourceName, path);
Assembly resolvedAssembly = Assembly.LoadFile(path);
return resolvedAssembly;
}
private static void ExtractEmbeddedAssembly(string manifestResourceName, string path) {
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(manifestResourceName)) {
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
using (FileStream fstream = new FileStream(path, FileMode.Create)) {
fstream.Write(buffer, 0, buffer.Length);
}
}
}
}
}
在EmbeddedReference.dll中
using System;
using System.Collections.Generic;
using System.Text;
namespace EmbeddedReference {
public static class MessageHelper {
public static void ShowMessage() {
Console.WriteLine("Hello World!");
}
}
}
标签:visual-studio-2010,assemblies,c,net 来源: https://codeday.me/bug/20191102/1989477.html