嵌入 .dlls - 在 C# 中解析程序集
本文关键字:程序集 dlls 嵌入 | 更新日期: 2023-09-27 18:36:29
我有一个.dll,我试图将资源嵌入到可执行文件中。以下两个问题有些帮助,但不是完全有帮助的:
将程序集嵌入到另一个程序集中
这似乎不像所写的那样工作; args。name 不能按写入方式使用,但即使已修复,程序仍会抱怨缺少.dll,指示程序集未正确加载。
在已编译的可执行文件中嵌入 DLL
以及以下答案之一中的链接:
http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/
但是,我的项目中没有任何类型的"App.xaml*"文件 - 我没有使用 WPF;我正在为我的可执行文件使用 WinForms(由于可执行文件的性质,更改实际上不是一个选项)。
因此,我正在寻找一组完整的指令,用于将类库作为资源嵌入可执行文件并从资源加载该.dll,而无需在嵌入资源之外使用.dll文件。
例如,简单地将"App.xaml"文件添加到 WinForms 项目是否可行,或者是否存在我不知道的负面交互?
谢谢。
编辑:这是我目前正在使用的:
/// <summary>
/// Stores the very few things that need to be global.
/// </summary>
static class AssemblyResolver
{
/// <summary>
/// Call in the static constructor of the startup class.
/// </summary>
public static void Initialize( )
{
AppDomain.CurrentDomain.AssemblyResolve +=
new ResolveEventHandler( Resolver ) ;
}
/// <summary>
/// Use this to resolve assemblies.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <returns></returns>
public static Assembly Resolver( object sender, ResolveEventArgs args )
{
Assembly executingAssembly = Assembly.GetExecutingAssembly( ) ;
if ( args.Name == null )
throw new NullReferenceException(
"Item name is null and could not be resolved."
) ;
if ( !executingAssembly.GetManifestResourceNames().Contains(
"Many_Objects_Display.Resources." +
new AssemblyName( args.Name ).Name.Replace( ".resources", ".dll" ) )
)
throw new ArgumentException( "Resource name does not exist." ) ;
Stream resourceStream =
executingAssembly.GetManifestResourceStream(
"Many_Objects_Display.Resources." +
new AssemblyName( args.Name ).Name.Replace( ".resources", ".dll" )
) ;
if ( resourceStream == null )
throw new NullReferenceException( "Resource stream is null." ) ;
if ( resourceStream.Length > 104857600)
throw new ArgumentException(
"Exceedingly long resource - greater than 100 MB. Aborting..."
) ;
byte[] block = new byte[ resourceStream.Length ] ;
resourceStream.Read( block, 0, block.Length ) ;
Assembly resourceAssembly = Assembly.Load( block ) ;
if ( resourceAssembly == null )
throw new NullReferenceException( "Assembly is a null value." ) ;
return resourceAssembly ;
}
}
您需要将代码放在主入口点中。像这样:
class Program
{
static Program()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static void Main(string[] args)
{
// what was here is the same
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
// the rest of sample code
}
}
不能只将 App.xaml 文件添加到 Windows 窗体应用程序。
另外,CurrentDomain_AssemblyResolve
的示例代码很奇怪,我会先尝试这段代码。我还没有测试过它,但它看起来更像我以前使用过的代码。