Based on the comment from Jon Skeet that this probably is not possible with editorconfig, I wrote a generic unit test for it.
using System.Text.RegularExpressions;
using Shouldly;
namespace Base.SharedTests.UnitTests;
public partial class CodeTests
{
[Fact]
public void AllFiles_WithCsExtension_ShouldHaveFileScopedNamespaces()
{
var solutionBasePath = Path.GetFullPath(
Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..")
);
var files = Directory
.GetFiles(solutionBasePath, "*.cs", SearchOption.AllDirectories)
.Where(f => !f.EndsWith("GlobalUsings.cs", StringComparison.Ordinal))
.Where(f => !f.EndsWith("Program.cs", StringComparison.Ordinal))
.Where(f => !f.Contains("/bin/", StringComparison.Ordinal))
.Where(f => !f.Contains("/obj/", StringComparison.Ordinal));
List<(string FileName, bool Result)> results =
[
.. files.Select(f =>
{
var text = File.ReadAllText(f);
var fileName = Path.GetFileName(f);
var result = NamespaceRegex().IsMatch(text);
return (fileName, result);
}),
];
results.ShouldAllBe(r => r.Result == true);
}
[GeneratedRegex(@"^\s*namespace\s+[A-Za-z0-9_.]+\s*;", RegexOptions.Multiline)]
private static partial Regex NamespaceRegex();
}