Powershell to recursively strip C# regions from files

Here’s a super quick little powershell snippet to strip regions out of all C# files in a directory tree. Useful for legacy code where people hide long blocks in regions rather than encapsulate it into smaller methods/objects.

dir -recurse -filter *.cs $src | foreach ($_) {
    $file = $_.fullname
    echo $file
    (get-content $file) | where {$_ -notmatch "^.*\#(end)?region.*$" } | out-file $file
}

Run this in your solution folder and support the movement against C# regions!

August 12, 2010

7 Comments

Pingback: DotNetShoutout

Omer Rauchwerger on August 12, 2010 at 10:41 am.

You can also run Regionerate’s command line utility with the “Remove All Regions” layout on any .sln / .csproj file.

Slava Agafonov on September 17, 2010 at 12:49 pm.

Very nice article. I have 200 regions in my code and I need to clean it up in one operation without any problems.

Richard on May 31, 2011 at 10:13 am.

@Omar: the current version of Regionerate (0.7.3.0) does not support removing #regions around using blocks.

Tim R on March 23, 2012 at 2:16 pm.

Thanks Rich. Found an easier way if some people in your team don’t want them all removed.

In VS:
Tools -> Options -> Text Editor -> C# -> Advanced -> Uncheck “Enter outlining mode when files open”

Now I don’t care if they are there :)

Leave a Reply