How to find the relative file path of a class file to csproj in SourceGenerator

Viewed 86

I am using SourceGenerator and analysing a class to create a string that needs to have the relative path of the class file to the csproj file.

I am able to find the absolute path of the class file using code below, but not the relative path

public class XamlControlAndPageFinder : ISyntaxContextReceiver
{

    public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
    {
        if (context.Node is ClassDeclarationSyntax userControl)
        {
             // This gives us the complete path and not relative path
             var filePath = userControl.SyntaxTree.FilePath;
        }
    }
}
1 Answers

You can walk the file system upwards until you find a .csproj file. Then calculate the relative path from it to your class file.

This will NOT work if you are using linked files outside of the main path, but it may be good enough for your scenario.

Related