我有一个 .dll,我试图将其作为资源嵌入到可执行文件中。以下两个问题有些帮助,但不是完全的帮助:
这似乎不像书面的那样工作;args.Name 不能像写的那样使用,但是即使它被修复了,程序仍然会抱怨缺少 .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 ;
}
}