You can access the file path from SyntaxTreeAction using Tree.FilePath off << 22>.
Once you have a path, you can analyze this and compare it with the name of all the NamesSpaceDeclarationSyntax node NamesSpaceDeclarationSyntax in the tree.
Unfortunately, I don't think there is a way to get the default namespace for a project at the moment.
Here is a brief sample that I put together and does what it can do so far. Handling / comparing the namespace path is rudimentary, and there is probably a better way to do this, but this should get you started.
public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction((compilationSyntax) => { compilationSyntax.RegisterSyntaxTreeAction((syntaxTreeContext) => { var semModel = compilationSyntax.Compilation.GetSemanticModel(syntaxTreeContext.Tree); var filePath = syntaxTreeContext.Tree.FilePath; if (filePath == null) return; var namespaceNodes = syntaxTreeContext.Tree.GetRoot().DescendantNodes().OfType<NamespaceDeclarationSyntax>(); var parentDirectory = System.IO.Path.GetDirectoryName(filePath); // This will only work on windows and is not very robust. var parentDirectoryWithDots = parentDirectory.Replace("\\", ".").ToLower(); foreach (var ns in namespaceNodes) { var symbolInfo = semModel.GetDeclaredSymbol(ns) as INamespaceSymbol; var name = symbolInfo.ToDisplayString(); if (!parentDirectoryWithDots.EndsWith(name.ToLower().Trim())) { syntaxTreeContext.ReportDiagnostic(Diagnostic.Create( Rule, ns.Name.GetLocation(), parentDirectoryWithDots)); } } }); }); }
source share