lundi 8 février 2016

What's the best way to get the namespaces in a WinMD file?

I'm looking to get all of the namespaces in a WinMD file programmatically. I would prefer a PowerShell or C#-based solution since I need it to be in a script, but any language will do as long as it gets the job done.

Here is the code I have right now, using Assembly.ReflectionOnlyLoadFrom:

var domain = AppDomain.CurrentDomain;
ResolveEventHandler assemblyHandler = (o, e) => Assembly.ReflectionOnlyLoad(e.Name);
EventHandler<NamespaceResolveEventArgs> namespaceHandler = (o, e) =>
{
    string file = WindowsRuntimeMetadata
        .ResolveNamespace(e.NamespaceName, Array.Empty<string>())
        .FirstOrDefault();

    if (file == null)
        return;

    var assembly = Assembly.ReflectionOnlyLoadFrom(file);
    e.ResolvedAssemblies.Add(assembly);
};

try
{
    // Load it! (plain .NET assemblies)
    return Assembly.LoadFrom(path);
}
catch
{
    try
    {
        // Hook up the handlers
        domain.ReflectionOnlyAssemblyResolve += assemblyHandler;
        WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve += namespaceHandler;

        // Load it again! (WinMD components)
        return Assembly.ReflectionOnlyLoadFrom(path);
    }
    finally
    {
        // Detach the handlers
        domain.ReflectionOnlyAssemblyResolve -= assemblyHandler;
        WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve -= namespaceHandler;
    }
}

For some reason, it doesn't seem to be working. When I run it, I'm getting a ReflectionTypeLoadException when I try to load WinMD files. (You can see this question for the full details.)

So my question is, what's the best way to go about doing this, if the Reflection APIs aren't working? How do tools like Visual Studio or ILSpy do this when you hit F12 on a WinRT type? Is there any way to do this from PowerShell?

TL;DR: How do I extract all of the namespaces from a WinMD file? Any language solution accepted.

Thanks.





Aucun commentaire:

Enregistrer un commentaire