Search code examples
c#.netreflectiongaccsharpcodeprovider

C#: finding path to PresentationCore.dll (and other assemblies) in the GAC


I need to reference various assemblies in a CSharpCodeProvider via calling ReferencedAssemblies.Add.

For some assemblies, it is sufficient to simply pass the assembly name - for example ReferencedAssemblies.Add("System.dll").

However, PresentationCore.dll is one of those where a full path to the assembly is required - which I may not necessarily know on the target machine.

Question:

How can I locate the definitive path to the (latest?) respective assembly - say, in the GAC?

Ideally, the solution would not only work for PresentationCore.dll, but also other assemblies such as PresentationFramework.dll, System.Xaml.dll or System.Windows.Forms.

Sources that didn't yield the intended results:

  • This solution would involve hard-coding a specific path, but the solution should be dynamic
  • Implementing this Windows API may work; but I don't know how - or if it would even help solve the above
  • This C++ question refers to where the GAC is found, but not how to get an actual file path

Solution

  • You can reference the assemblies in the code that should do the resolving. Then the runtime will tell you the assembly location:

    typeof([TypeKnownToBeInTheDesiredAssembly]).Assembly.CodeBase

    for example, to find the System.Xml.dll:

    string codeBase = typeof(System.Xml.XmlDocument).Assembly.CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
    Console.WriteLine(path);
    

    [ref]

    On my system:

    C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll