I am writing a metadata extractor for C# projects. I'm not using MSBuildWorkspace, instead using CSharpSyntaxTree.ParseText() and CSharpCompilation.Create().
Checking the diagnostics from the compilation I noticed that I was missing a number of assembly references:
_references.Add( MetadataReference.CreateFromFile( Assembly.Load( "netstandard, Version=2.0.0.0" ).Location ) );
_references.Add( MetadataReference.CreateFromFile( Assembly.Load( "System.Runtime" ).Location ) );
_references.Add( MetadataReference.CreateFromFile( typeof( object ).Assembly.Location ) );
_references.Add( MetadataReference.CreateFromFile( Assembly.Load( "System.IO.FileSystem" ).Location ) );
_references.Add( MetadataReference.CreateFromFile( Assembly.Load( "System.Runtime.Extensions" ).Location ) );
_references.Add( MetadataReference.CreateFromFile( Assembly.Load( "System.Collections" ).Location ) );
_references.Add( MetadataReference.CreateFromFile( Assembly.Load( "System.Private.Uri" ).Location ) );
where _references
is a collection I use in the compilation:
compilation = CSharpCompilation.Create( ProjectDocument.AssemblyName )
.AddReferences( _references.ToArray() )
.AddSyntaxTrees( trees );
and trees
are the syntax trees I'm compiling.
My question is this: is there a way to determine, from the syntax trees or the .csproj file, exactly what references are needed? I do this for nuget packages added to the project file by parsing the various <ProjectReference>
nodes. But I'm not sure how to do that for the other references.
If you can run a NuGet restore then the project.assets.json
file should have all the information you need