C# – Mimicking assembly resolution of the msbuild process

assembly-resolutioncmsbuild

I am writing a validation tool that checks the versions of files referenced in a project. I want to use the same resolution process that MSBuild uses.

For example, Assembly.Load(..) requires a fully-qualified assembly name. However, in the project file, we may only have something like "System.Xml". MSBuild probably uses the project's target framework version and some other heuristics to decide which version of System.Xml to load.

How would you go about mimicking (or directly using) msbuild's assembly resolution process?

In other words, at run-time, I want to take the string "System.Xml", along with other info found in a .csproj file and find the same file that msbuild would find.

Best Answer

If you target the Framework version you want to be compatible with instead of targeting 3.5, Visual Studio 2008 SP1 and FxCop 1.36 RTM added rule CA 1903: Use only API from targeted framework to ensure you stay compatible with the target framework version. Turning that rule on and treating it as an error will fail your Build and provide the behavior you want.

Here is sample code demonstrating a violation when you are targeting framework version 2:

using System.Runtime;

class Program
{
    static void Main()
    {
        GCSettings.LatencyMode = GCLatencyMode.LowLatency;
    }
}