开发者

How to execute WPF assembly from memory?

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(ent开发者_如何学JAVAry.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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜