Question

I am using NRefactory to attempt to parse all compile files listed in in a .csproj file, and want to be able to resolve all types in a project.

I can't resolve all types though without adding in the assembly references that the .csproj also contains, which is what I am struggling with.

Excerpt from .csproj:

<ItemGroup>
    <Reference Include="Microsoft.Xna.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553, processorArchitecture=x86" />
    <Reference Include="Microsoft.Xna.Framework.Game, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553, processorArchitecture=x86" />
    <Reference Include="mscorlib" />
    <Reference Include="System" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Core" />
</ItemGroup>

As can be seen the XNA references give a fullname, so I can easily get their assembly using Type.GetType("fullname").Assembly. But passing in System or mscorlib without the publickey just returns null.

How am I able to get the full type name of System just from the word System and the other information present in a .csproj file?

Was it helpful?

Solution

Which copy of System.dll do you actually want to load? One that is usable at runtime? Or the one used by the C# compiler?

If the project targets .NET 4.0, the C# compiler uses a different reference assembly than for projects targeting .NET 4.5. However, at runtime, both use the same assembly (as the .NET 4.5 installation overwrites .NET 4.0).

To get the same version as used by the C# compiler, the best solution is to ask MSBuild (via Microsoft.Build.dll) to resolve the assembly reference. The sample application on the NRefactory CodeProject article uses this approach, feel free to copy the code from there.

Getting the correct runtime assembly is impossible in general, as applications can re-configure how assemblies are loaded (app.config or AppDomain.AssemblyResolve event handlers). However a good approximation could be to use MSBuild for determining the full assembly name, and then pass that into Assembly.Load() to let .NET take care of the runtime loading logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top