One way to do this is to build a parser and a prettyprinter.
The parser reads the source and builds an AST capturing the essence of
the program structure. The prettyprinter takes the tree,
and regenerates output based on the structure; thus it is "easy"
to get structured output. As a key hint, for each level of
language structure (classes, methods, blocks, loops, conditionals),
the prettyprinter can indent the prettyprinted text to give
good indentation structure.
Parsing and prettyprinting are both pretty complicated topics.
Rather than repeat all that here, you can see
my SO answer on how to parse, with follow on discussion on how to build an AST. Prettyprinting is not so well known,
but this SO answer of mine provides a pretty complete description
of how to do it.
Then you have the complication of determining the actual grammar of VB.net. That requires a lot of work to extract from the reference documentation... and it isn't quite right, so you need to validate your parser against a lot of code to convince yourself it right. This part is unfortunately just sweat.
Given a prettyprinter program, OP can simply launch it as a process to format a file.
If you do all that, then yes you can format VB.net text. Our (standalone) VB.net formatter ("DMSFormat ...") does the above to achieve prettyprinting.
Given the file "vb_example.net":
Module Test
Public Shared Function CanReachPage(page As String) As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead(page)
Return True
End Using
End Using
Catch
Return False
End Try
End Function
End Module
The following:
C:>DMSFormat VisualBasic~VBdotNet C:\temp\vb_example.net
produces:
VisualBasic~VBdotNet Formatter/Obfuscator Version 1.2.1
Copyright (C) 2010 Semantic Designs, Inc
Powered by DMS (R) Software Reengineering Toolkit
Parsing C:\temp\vb_example.net [encoding ISO-8859-1]
Module Test
Public Shared Function CanReachPage(page As String) As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead(page)
Return True
End Using
End Using
Catch
Return False
End Try
End Function
End Module
which is identical to what OP wanted in his example.
You can easily direct the formatted program content to a file.
You can give the tool a project file, and it will format as many files as you specify
in the project file at once.
The formatter integrates a complete VB.net parser,
and our own prettyprinting machinery. It parses
the source text precisely (including strange character
encodings). Because it uses a reliable parser and prettyprinter, it will not break the code.
The eval version works on files of a few hundred lines of code. It might be just what you need.
I'd provide a link but SO seems to dislike that. You can find this through my bio.
Using
then I must indent one level" etc etc – Wimbush