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 12th, 2010 | 5 Comments
5 Responses to “Powershell to recursively strip C# regions from files” Leave your Comment
  1. DotNetShoutout says:

    Powershell to recursively strip C# regions from files…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. Omer Rauchwerger says:

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

  3. Tweets that mention Richard Dingwall » Powershell to recursively strip C# regions from files -- Topsy.com says:

    [...] This post was mentioned on Twitter by Johan Broberg and Rich, Jim Poshible. Jim Poshible said: RT @dingwallr: New blog post: Powershell to recursively strip C# regions from files http://bit.ly/ckeBA5 [...]

  4. Richard Dingwall » Visual Studio projects are for deployment, not organising code says:

    [...] fact, removing them has become one of the first steps I take when inheriting a legacy code base. If I were writing a book on refactoring Visual Studio [...]

  5. Slava Agafonov says:

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

Leave a reply

We love to hear your views.