2

In VS2022 I turned on the very useful feature "Run Code Cleanup profile on Save". With this option on, every unneeded using statement in code gets removed automatically on save.

Now I would like to create a .cs file that contains a bounch of global using statements and nothing else. I think that having them in a separate, dedicated file helps keeping project clean.

However, since these global using statements are not used in the .cs file itself, they get removed every time I save the file.

Is there a way to skip cleanup in some circumstances? For example:

  • For a specific file
  • For global using statements
  • When I save with a given keyboard/mouse shortcut (ex. by holding SHIFT or similar when clicking Save)

The first two options would be better because would work also if I run cleanup on the entire project.

UPDATE

I found out that this happens only in NET (8?) projects. global using directives in a NET Framework 4.6.2 project are not removed by code cleanup.

Thank you

2 Answers 2

1

There are at least two options I see:

  1. Exclude the file with global usings from cleanup in editor config. Add the following line to it (for example for file in the project root with name GlobalUsings.cs):

    [GlobalUsings.cs]
    generated_code = true
    

    Docs for the feature, available starting with Visual Studio 2019 16.5.

  2. Move the global usings to the csproj file (showing example for System.Globalization namespace):

    <ItemGroup>
        <Using Include="System.Globalization"/>
    </ItemGroup>
    
Sign up to request clarification or add additional context in comments.

2 Comments

Great! I excluded my file from cleanup. Thank you!
UPDATE: I found out that this happens only in NET project. global using directives in a NET Framework 4.6.2 project are not removed by code cleanup.
0

You can consider configuring the cleanup actions you need to perform in the Code cleanup settings, such as Remove unnecessary Imports or usings.

enter image description here

You can also write your own code-style rule options and add in into your code cleanup configuration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.