The following code is tested on Visual Studio 2022 17.7 and uses the Community toolkit for Visual Studio extensions. Install the item templates to create a new extension project.
After creating a new extension, reference the Microsoft.VisualStudio.LanguageServices package. It provides the VisualStudioWorkspace class, which gives access to the current Roslyn compilation. With this package added, your project file should include the following NuGet packages:
XML
<ItemGroup>
<PackageReference Include="Community.VisualStudio.VSCT" Version="16.0.29.6" PrivateAssets="all" />
<PackageReference Include="Community.VisualStudio.Toolkit.17" Version="17.0.430" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.VisualStudio.LanguageServices" Version="4.6.0" />
<PackageReference Include="Microsoft.VSSDK.BuildTools" Version="17.0.5232" />
</ItemGroup>
The following code shows how to retrieve the System.Console type from the current compilation using VisualStudioWorkspace:
C#
var workspace = await VS.GetMefServiceAsync<VisualStudioWorkspace>();
if(workspace?.CurrentSolution != null)
{
foreach (var project in workspace.CurrentSolution.Projects)
{
// Not all projects have a compilation object, so you need to check if it's supported first.
// Remember that Visual Studio supports multiple project types, not only .NET projects.
if (project.SupportsCompilation)
{
var compilation = await project.GetCompilationAsync();
var type = compilation.GetTypeByMetadataName("System.Console");
}
}
}
#Additional resources
Do you have a question or a suggestion about this post? Contact me!