如何在SourceGenerator中查找类文件到csproj的相对文件路径

发布于 2025-01-10 04:56:01 字数 569 浏览 3 评论 0原文

我正在使用 SourceGenerator 并分析 class 来创建一个字符串,该字符串需要具有类文件到 csproj 文件的相对路径。

我可以使用下面的代码找到 class 文件的绝对路径,但不能找到相对路径

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;
        }
    }
}

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;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

压抑⊿情绪 2025-01-17 04:56:01

您可以向上遍历文件系统,直到找到 .csproj 文件。然后计算从它到类文件的相对路径。

如果您在主路径之外使用链接文件,这将不起作用,但它可能足以满足您的场景。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文