Reduce spaces from avery line in a text file. VB 2008
Hi.
I am a newbie and i need some code that will load a text file into a string scan through it checking each line and reduce the spaces it has in that line and then write it back to the text file.
For example:
It finds a line like below
drmk.sys = 100,,,,,,,4,0,3
reduces the amount of spaces so it looks like:
drmk.sys = 100,,,,,,,4,0,3
Many Thank for any help.
TStrike

Eamonn22 reputationPosted Jul 27, 2009, 11:52 AM EDT
There may be a neater way of doing this, my VB is a little rusty.
'Open a filestream to the input file Using fileIn As New System.IO.FileStream("d:\temp\test.txt", IO.FileMode.Open, System.IO.FileAccess.Read) 'Initialize a StreamReader to read the file Using streamIn As New System.IO.StreamReader(fileIn) 'This RegEx will be ued to srtip out ALL the spaces in an input string Dim regEx As System.Text.RegularExpressions.Regex regEx = New System.Text.RegularExpressions.Regex("\ *") 'Loop through the file line by line and replace the spaces, writing the result ot a new output file While Not streamIn.EndOfStream 'Open a filestream to the output file Using fileOut As New System.IO.FileStream("d:\temp\test2.txt", IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write) 'Open a StreamWriter to write out the updated line Using StreamOut As New System.IO.StreamWriter(fileOut) Dim line As String line = streamIn.ReadLine() line = regEx.Replace(line, "") StreamOut.WriteLine(line) End Using ' Disposes of streamOut End Using ' Disposes of fileOut End While End Using ' Disposes of streamIn End Using ' Disposes of fileIn