3

I am currently reading in a text file in VB.Net using

Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(file)

File contains several lines of text and when I read in the text file, it knows that they are on separate lines and prints them out accordingly.

However, when I try to split fileReader into an array of the different lines, the line break seems to stay there, even if I use Split(ControlChars.Cr) or Split(ControlChars.NewLine). It will successfully split it into the separate lines but when I display it, it will "push" the text down a line, like the line break is still there...

Does anyone have any ideas on what is going on and how I can remove these "invisible" control chars.

Text File:

Test1
Test2
Test3
Test4

fileReader:

Test1
Test2
Test3
Test4

lines() printout

Test1

Test2

Test3

Test4

Kyle Uithoven
  • 2,414
  • 5
  • 30
  • 43

4 Answers4

5

Use trim() on each line, it'll remove extraneous whitespace.

Cyclone
  • 17,939
  • 45
  • 124
  • 193
2

The System.IO.File class has a ReadAllLines method that will actually give you back an array of strings, one per line.

If that method doesn't work, either, I would examine exactly what bytes are causing you issues. In the watch window, you can do a System.Text.Encoding.ASCII.GetBytes (sampleLine) and examine exactly what you are working with.

I'm assuming you are using ASCII encoding, if not, you'll need to swap out ASCII with the correct option, and then modify your file read to read based on that encoding, as well.

Evan
  • 2,441
  • 23
  • 36
1

As mentioned use the Readalllines method to have it split automatically.

The problem you are having is PC ASCII files are usually split with a carriage return and a new line, splitting on just one will leave the other. You can split and trim as mentioned or use the other split that splits on strings instead of chars.

dim s() as string = Split(fileReader ,vbCrLf)

Trim will remove spaces from the data as well, depending on your situation that could be a problem for you.

dwidel
  • 1,264
  • 1
  • 12
  • 22
0

Ran into a similar problem recently. The Trim() doesnt work because the extra lines are already there after doing the split (or using File.ReadAllLines). Here's what worked for me:

    Dim allText As String = System.IO.File.ReadAllText(filePath)
    allText = allText.Replace(Chr(13), "")
    Dim lines As String() = allText.Split(vbLf)

Chr(13) is the Control-M character that result in extra lines using Split() or File.ReadAllLines.

Unmesh
  • 587
  • 4
  • 4