Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created October 7, 2015 21:06
Show Gist options
  • Select an option

  • Save vendettamit/5a1a71eba84c741b397a to your computer and use it in GitHub Desktop.

Select an option

Save vendettamit/5a1a71eba84c741b397a to your computer and use it in GitHub Desktop.
This is a sample code that can be used to find references using Roslyn version Microsoft.CodeAnalysis 1.0.0
class ReferenceFinder
{
public void Find(string methodName)
{
string solutionPath = @"C:\Users\achoudhary\Documents\Visual Studio 2013\Projects\ConsoleForEverything\ConsoleForEverything.sln";
var msWorkspace = MSBuildWorkspace.Create();
List<ReferencedSymbol> referencesToMethod = new List<ReferencedSymbol>();
Console.WriteLine("Searching for method \"{0}\" reference in solution {1} ", methodName, Path.GetFileName(solutionPath));
ISymbol methodSymbol = null;
bool found = false;
//You must install the MSBuild Tools or this line will throw an exception.
var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
var model = document.GetSemanticModelAsync().Result;
var methodInvocation = document.GetSyntaxRootAsync().Result;
InvocationExpressionSyntax node = null;
try
{
node = methodInvocation.DescendantNodes().OfType<InvocationExpressionSyntax>()
.Where(x => ((MemberAccessExpressionSyntax)x.Expression).Name.ToString() == methodName).FirstOrDefault();
if (node == null)
continue;
}
catch(Exception exception)
{
// Swallow the exception of type cast.
// Could be avoided by a better filtering on above linq.
continue;
}
methodSymbol = model.GetSymbolInfo(node).Symbol;
found = true;
break;
}
if (found) break;
}
foreach (var item in SymbolFinder.FindReferencesAsync(methodSymbol, solution).Result)
{
foreach (var location in item.Locations)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Project Assembly -> {0}", location.Document.Project.AssemblyName);
Console.ResetColor();
}
}
Console.WriteLine("Finished searching. Press any key to continue....");
}
}
}
@M-Yankov

M-Yankov commented Feb 2, 2018

Copy link
Copy Markdown

Invoking SymbolFinder.FindReferencesAsync(methodSymbol, solution).Result throws an exception An item with the same key has already been added.

Microsoft.CodeAnalysis version="2.6.1"

@ChaitaliSen

Copy link
Copy Markdown

Can we get line number from this method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment