如何在SourceGenerator中查找类文件到csproj的相对文件路径
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以向上遍历文件系统,直到找到
.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.