不多说了,网上虽然有许多代码,但是是在Silverlight 2 RC0以前的版本才能用,现在Silverlight到了2.0正式版了,代码必须变一变了。不过国内好像关注的人不多,一点相关的资料都没有。下面是代码。
- public static Assembly LoadAssemblyFromXap(Stream packageStream, String assemblyName)
- {
- StreamResourceInfo streamInfo = Application.GetResourceStream(
- new StreamResourceInfo(packageStream,
- "application/binary"),
- new Uri(assemblyName, UriKind.Relative));
- return (new AssemblyPart()).Load(streamInfo.Stream);
- }
这个完成了从XAP中加载某个程序集。但是有个问题,一个XAP文件中可能包含多个程序集(多个DLL),那么就是需要加载整个XAP文件。不多说,还是上代码。
- public static void LoadXap(Stream packageStream)
- {
- Stream stream = Application.GetResourceStream(
- new StreamResourceInfo(packageStream, null),
- new Uri("AppManifest.xaml", UriKind.Relative)).Stream;
- String appManifestString = new StreamReader(stream).ReadToEnd();
- XElement deploymentRoot = XDocument.Parse(appManifestString).Root;
- List<XElement> deploymentParts = (from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList();
- AssemblyPart assemblyPart = new AssemblyPart();
- foreach (XElement xElement in deploymentParts)
- {
- string source = xElement.Attribute("Source").Value;
- StreamResourceInfo streamInfo = Application.GetResourceStream(
- new StreamResourceInfo(packageStream,
- "application/binary"),
- new Uri(source, UriKind.Relative));
- assemblyPart.Load(streamInfo.Stream);
- }
- }
这样先加载整个XAP文件,然后再加载某个程序集吧,这样就完美了。当然程序还可以再改进下,大家自己看着办吧。
PS:多次加载没有关系的,程序集是有HASH值的,不会有冲突或不兼容的问题。
备注:未经本人授权,此文章不得转载。---GameDevBoy