Removing Charaters from Text files

Bigbadborris

Active member
Joined
Aug 21, 2013
Messages
35
Programming Experience
Beginner
HI

Me again

I am trying to remove the first 7 characters every line of a text file.

I have this code so far


Dim FILE_NAME AsString = "C:\DRITXT\TRADE.txt"

Dim FILE_NAMEOUT AsString = "C:\DRITXT\TRADE2.txt"

Dim TextLine AsString

Dim TextTrim AsString

Dim objReader AsNew System.IO.StreamReader(FILE_NAME)

DoWhile objReader.Peek() <> -1
TextLine = TextLine & objReader.ReadLine() & vbNewLine
TextTrim = TextLine.Remove(0, 7)

Dim objWriter AsNew System.IO.StreamWriter(FILE_NAMEOUT)
objWriter.WriteLine(TextTrim)
objWriter.Close()

Loop

The problem is this only removes the first 7 characters from the first line only.

Can someone tell me where I am going wrong

Many Thanks
 
I think you have a couple of things backwards going on here.
First glaring thing that stands out is you're declaring a new StreamWriter inside the loop that's reading from the input file.
Second thing I see is you're building each line into a single variable, then always taking off the first 7 chars from the same line.

What I would recommend is declaring both StreamReader and the StreamWriter outside of the loop, then as you read in each line from the input file grab a SubString(8) to grab everything on that line starting with the 8th character and put that right into a WriteLine on the output file.

The psuedo code would be:
Declare Reader
Declare Writer

Loop the Reader while Peek <> -1
Writer.WriteLine(Reader.ReadLine.SubString(8)
End Loop

Close Writer
Close Reader

Dispose Writer
Dispose Reader

It also wouldn't hurt to put all of that in a Try/Catch, because things like IO errors and/or file not existing for the reader or the destination folder can't be written to for the output file could all cause this stuff to fail for you.
 
Thank you JuggaloBrotha

Dim FILE_NAME AsString = "K:\NETWORK\TRADELIST\TRADE.txt"
Dim FILE_NAMEOUT AsString = "K:\NETWORK\TRADELIST\TRADE2.txt"
Dim objRead As New StreamReader(FILE_NAME)
Dim objWriter As New StreamWriter(FILE_NAMEOUT)

DoWhile objRead.Peek <> -1
objWriter.WriteLine(objRead.ReadLine.Substring(7))
Loop
objRead.Close()
objWriter.Close()

This worked perfect


 
Thank you JuggaloBrotha

Dim FILE_NAME AsString = "K:\NETWORK\TRADELIST\TRADE.txt"
Dim FILE_NAMEOUT AsString = "K:\NETWORK\TRADELIST\TRADE2.txt"
Dim objRead As New StreamReader(FILE_NAME)
Dim objWriter As New StreamWriter(FILE_NAMEOUT)

DoWhile objRead.Peek <> -1
objWriter.WriteLine(objRead.ReadLine.Substring(7))
Loop
objRead.Close()
objWriter.Close()

This worked perfect


I would still put it inside a Try/Catch and be sure to dispose of them when you're done.

Also a forum tip, to post code and have it show colored and formatted like it is in VS use [xcode=vb.net]Your code here[/xcode] and it'll format everything like so:
Private Sub SomeRoutine
    Dim Number As Integer = 1
    'Some other code here
End Sub
 
Back
Top