如何从内存执行WPF程序集?
如果 ms
变量是 MemoryStream
并且包含 .Net 程序集,通常会像这样运行它:
var asm = Assembly.Load(ms.ToArray());
var entry = asm.EntryPoint;
var inst = asm.CreateInstance(entry.Name);
entry.Invoke(inst, null);
这在控制台应用程序和 Windows 窗体应用程序上运行良好,但是,WPF应用程序抛出异常:
Exception has been thrown by the target of an invocation.
使用 System.IO.IOException
类型的内部异常:
Cannot locate resource 'mainwindow.xaml'.
堆栈跟踪确实很大,但从一开始就猜测,从内存加载时它无法找到资源:
at MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access)
at System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
at System.IO.Packaging.PackagePart.GetStream()
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__1(Object unused)
[...]
怎么可能我修好这个吗?
If the ms
variable is a MemoryStream
and contains a .Net assembly, you would normally run it like this:
var asm = Assembly.Load(ms.ToArray());
var entry = asm.EntryPoint;
var inst = asm.CreateInstance(entry.Name);
entry.Invoke(inst, null);
This works well on console applications and windows forms applications, however, WPF applications throw an exception:
Exception has been thrown by the target of an invocation.
With the inner exception of type System.IO.IOException
:
Cannot locate resource 'mainwindow.xaml'.
The stacktrace is really big, but guessing from the start, it can't locate the resources when loaded from memory:
at MS.Internal.AppModel.ResourcePart.GetStreamCore(FileMode mode, FileAccess access)
at System.IO.Packaging.PackagePart.GetStream(FileMode mode, FileAccess access)
at System.IO.Packaging.PackagePart.GetStream()
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__1(Object unused)
[...]
How could I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您从 MemoryStream 动态加载程序集时,其工作目录将是您自己的程序集的工作目录。该目录不太可能包含程序集引用的 XAML 标记文件。
尝试将 Environment.CurrentDirectory 设置为包含必要的 XAML 的新目录,至少在程序集加载和类实例化期间是如此。
When you load an assembly dynamically from a MemoryStream, its working directory will be that of your own assembly. That directory is unlikely to contain the XAML markup files referred to by the assembly.
Try setting your Environment.CurrentDirectory to a new directory containing the necessary XAML, at least for the duration of the assembly loading and class instantiation.
正如 SAKryukov 在代码项目 此处的建议,我将 WPF 应用程序制作成一个带有自定义入口点的库,然后用我的第二个应用程序调用该入口点。问题似乎在于 App.xaml 实现 starturi 的方式
As suggested by SAKryukov on codeproject here, I made the WPF app into a library with a custom entry point which I then invoke with my 2nd application. The problem seems to lie with the way that App.xaml implements the starturi