Microsoft.CodeAnalysis
Microsoft.CodeAnalysis.MSBuild
, System.Linq
and Microsoft.CodeAnalysis.CSharp.Syntax
Main
method:// Declaring a variable with the current project file path.
const string projectPath = @"C:\<your path to the project\<project file name>.csproj";
// Creating a build workspace.
var workspace = MSBuildWorkspace.Create();
// Opening this project.
var project = workspace.OpenProjectAsync(projectPath).Result;
// Getting the compilation.
var compilation = project.GetCompilationAsync().Result;
// As this is a simple single file program, the first syntax tree will be the current file.
var syntaxTree = compilation.SyntaxTrees.First();
// Getting the root node of the file.
var rootSyntaxNode = syntaxTree.GetRootAsync().Result;
// Finding all the local variable declarations in this file and picking the first one.
var firstLocalVariablesDeclaration = rootSyntaxNode.DescendantNodesAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
// Getting the first declared variable in the declaration syntax.
var firstVariable = firstLocalVariablesDeclaration.Declaration.Variables.First();
// Getting the text of the initialized value.
var variableInitializer = firstVariable.Initializer.Value.GetFirstToken().ValueText;
// This will print to screen the value assigned to the projectPath variable.
Console.WriteLine(variableInitializer);
Console.ReadKey();
When running the project, you will see the variable declared on top printed to the screen. This means that you successfully self analysed a project and found a variable in it.