Search code examples
c#visual-studio.net-corevisual-studio-2019

List unreferenced files in Visual Studio 2019?


I have been experimenting a lot inside a solution containing only .NET Core 3.1 projects, and I noticed that there was a lot of unnecessary/unused code as a result.

Is there a way to list all the code inside my solution that isn't referenced anywhere else?

I'm aware that Visual Studio 2019 has the CodeLens feature that shows if a piece of code is referenced, but checking it for every single file manually is obviously not what I'm going for.

In existing answers for older versions of Visual Studio, the FxCop tool is mentioned a lot but as you can see on the Microsoft Page, it's no longer being updated. I also tried to run Code Analysis on my solution, but since I couldn't configure the analysis parameters for my solution, that didn't lead anywhere either. I even tried to configure code analysis on the project level, but Visual Studio didn't recognize my project as a candidate for analysis.


Solution

  • You can use the RuleSet from this answer to make your CodeAnalysis show you unused code:

    <?xml version="1.0" encoding="utf-8"?>
    <RuleSet Name="Dead Code Rules" Description=" " ToolsVersion="12.0">
      <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
        <Rule Id="CA1801" Action="Warning" />
        <Rule Id="CA1804" Action="Warning" />
        <Rule Id="CA1811" Action="Warning" />
        <Rule Id="CA1812" Action="Warning" />
        <Rule Id="CA1823" Action="Warning" />
      </Rules>
      <Rules AnalyzerId="Microsoft.Analyzers.NativeCodeAnalysis" RuleNamespace="Microsoft.Rules.Native">
        <Rule Id="C6259" Action="Warning" />
      </Rules>
    </RuleSet>
    

    Edit: You can use this step by step guide to build your RuleSet.

    Edit 2: Since the step by step guide is outdated, here is a new way of activating the needed rules:

    1. Go to the properties page of your project (right click -> Properties)
    2. Go to "Code Analysis", the last tab
    3. Click "Configure"
    4. Enter "unused" and activate all the rules that you want
    5. On the right, optionally set the Action to "Error" for extra attention
    6. Save (ctrl+s)

    Edit 3: We will keep the ruleset but it turns out I had an old project and on new ones, you need to do the following:

    1. If your target framework is below .NET5, install Microsoft.CodeAnalysis.FxCopAnalyzers Microsoft.CodeAnalysis.NetAnalyzers from NuGet (FxCop was deprecated)

    2. If you haven't already, add a file .editorconfig to you solution

    3. Enable the rules you want like this:

      [*.cs]
      # Avoid unused private fields
      dotnet_diagnostic.CA1823.severity = error

    in the editorconfig file to activate them.