0

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.

Mark Olbert
  • 6,584
  • 9
  • 35
  • 69
  • Is it feasible to run a NuGet restore on your project? If it is then it sounds like the `project.assets.json` file may have what you need – rbennett485 Feb 25 '20 at 13:23
  • LOL! Thanx, @rbennett485; I should've thought of that myself as I parse that file for other reasons. If you offer your idea as an answer I'd be pleased to accept it as such. – Mark Olbert Feb 25 '20 at 16:32
  • @rbennett485 may I refer you to https://stackoverflow.com/questions/60404294/resolving-assembly-references-in-roslyn? It's a related question that I'm hoping you may have some insights on. – Mark Olbert Feb 25 '20 at 22:47
  • not sure about your other question I'm afraid – rbennett485 Feb 28 '20 at 09:57

1 Answers1

1

If you can run a NuGet restore then the project.assets.json file should have all the information you need

rbennett485
  • 1,907
  • 15
  • 24