来自外部程序集的ResourceDictionary [从UnmanagedMemoryStream读取对象]

时间:2016-04-17 10:30:35

标签: c# .net wpf reflection

我在下面的代码中有一个UnmanagedMemoryStream,我怎样才能让对象从deserilizing它。我试图从Resource获得Assembly(rd.xaml):

string address = @"WpfControlLibrary1.dll";
Assembly skinAssembly = Assembly.LoadFrom(address);
string name = skinAssembly.GetName().Name +".g";
var manager = new ResourceManager(name, skinAssembly);
ResourceSet rs = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true);

UnmanagedMemoryStream stream = (UnmanagedMemoryStream)rs.GetObject("rd.baml", true);

我无法将deserialize Stream的内容转换为.net Object(在上述情况下为Resource Dictionary)。我怎么能这样做?

PS: BinaryFormatterDeserialize操作时抛出异常。

1 个答案:

答案 0 :(得分:1)

以下是我使用优化代码完成此操作的方法:

public ResourceDictionary GetResourceDictionary(string assemblyName)
    {
        Assembly asm = Assembly.LoadFrom(assemblyName);
        Stream stream = asm.GetManifestResourceStream(asm.GetName().Name + ".g.resources");            
        using (ResourceReader reader = new ResourceReader(stream))
        {
            foreach (DictionaryEntry entry in reader)
            {
                var readStream = entry.Value as Stream;
                Baml2006Reader bamlReader = new Baml2006Reader(readStream);
                var loadedObject = System.Windows.Markup.XamlReader.Load(bamlReader);
                if (loadedObject is ResourceDictionary)
                {
                    return loadedObject as ResourceDictionary;
                }
            }
        }
        return null;
    }

<强> 输出:

output

  

我想从外部程序集/另一个项目中读取ResourceDictionary,以便我可以将其Resources重复到/*float left*/ .left { float: left; /*left in our text*/ margin: 3px; /*space around the image*/ } @media (max-width: 793px;) { img { float:none; } }   使用。