嵌入.dll – 用C#解决程序集
我有一个.dll我试图将其作为资源嵌入可执行文件中。 以下两个问题有些帮助,但不是完整的帮助:
将组件嵌入另一个组件中
这似乎不像书面那样有效; args.Name不能像写的一样使用,但是即使它被修复了,程序仍然会抱怨缺少.dll,表明程序集没有正确加载。
将DLL嵌入已编译的可执行文件中
以及其中一个答案中的链接:
但是,我的项目中没有任何“App.xaml *”文件 – 我没有使用WPF; 我正在使用WinForms作为我的可执行文件(由于可执行文件的性质,更改不是一个真正的选项)。
因此,我正在寻找一套完整的指令,用于将类库作为资源嵌入可执行文件中,并从资源中加载.dll,而不需要嵌入式资源之外的.dll文件。
例如,简单地将“App.xaml”文件添加到WinForms项目是否可行,或者是否存在我不知道的负面交互?
谢谢。
编辑:这是我目前正在使用的:
/// /// Stores the very few things that need to be global. /// static class AssemblyResolver { /// /// Call in the static constructor of the startup class. /// public static void Initialize( ) { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler( Resolver ) ; } /// /// Use this to resolve assemblies. /// /// /// /// 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
示例代码很奇怪,我会首先尝试这个代码。 我没有测试它,但它看起来更像我以前使用过的代码。