Search code examples
c#.netsourcegenerators

How to Find File Path of Class Declaration in a Source Generator


Title pretty much explains it. I am writing a source generator and would like to know how to find the file path of a given ClassDeclarationSyntax node. Here is an example of how I'd like to be able to use it.

IEnumerable<SyntaxNode> allNodes = compilation.SyntaxTrees.SelectMany(s => s.GetRoot().DescendantNodes());
IEnumerable<ClassDeclarationSyntax> allClasses = allNodes.Where(d => d.IsKind(SyntaxKind.ClassDeclaration))
                                                         .OfType<ClassDeclarationSyntax>();
IEnumerable<string> filePaths = allClasses.Select(x=> x.GetFilePath());

Solution

  • You can use the following code to get the containing file path:

    SyntaxNode node = ...;
    _ = node.SyntaxTree.FilePath;
    _ = node.GetLocation().SourceTree?.FilePath // SourceTree can be null