Checking the Name of the File You are Analyzing

Sep 10, 2015

There are times when writing an analyzer that you may also want to get information about the file that contains some code you are analyzing. This information is available from Roslyn in the SyntaxTree and provides access to things like the file encoding and the file name.

Lets say we wanted to create an analyzer that ensured all of the compilable files in our solution had file names that started with an uppercase letter. To do this, we would first register a SyntaxTreeAction:

context.RegisterSyntaxTreeAction((syntaxTreeContext) =>
{
});

Inside that action, we will get the file path and ensure it is not null. It could be null for a few reasons, mainly when dynamically compiling snippets of code, so we will just guard against that:

Those are the basics for accessing file information from an analyzer. If you want to see an example of an analyzer that looks at the encoding of the file, you can look at SA1412StoreFilesAsUtf8 in the StyleCopAnalyzers GitHub project.