Problem with File IO and splitting strings with Environment.NewLine in VB.Net

Posted by Senthil on Stack Overflow See other posts from Stack Overflow or by Senthil
Published on 2010-04-10T14:33:56Z Indexed on 2010/04/10 14:43 UTC
Read the original article Hit count: 669

Filed under:
|
|

Hi,

I was experimenting with basic VB.Net file read/write and encountered this problem. I don't know whether it has something to do with the File IO or the String splitting.

I am writing text to a file like so

Dim sWriter As New StreamWriter("Data.txt")
sWriter.WriteLine("FirstItem")
sWriter.WriteLine("SecondItem")
sWriter.WriteLine("ThirdItem")
sWriter.Close()

Then, I am reading the text from the file

Dim sReader As New StreamReader("Data.txt")
Dim fileContents As String = sReader.ReadToEnd()
sReader.Close()

Now, I am splitting the fileContents variable using Environment.NewLine and saving the returned String array.

Dim tempStr() As String = fileContents.Split(Environment.NewLine)

When I print the array, I get some weird results

For Each str As String In tempStr
  Console.WriteLine("*" + str + "*")
Next

I added the *'s to the beginning and end to find out what is going on. Since NewLine is used as the delimiter, I expect the strings in the array to NOT have any NewLine's. But the output was this -

*FirstItem*
*
SecondItem*
*
ThirdItem*
*
*

Shouldn't it be this -

*FirstItem*
*SecondItem*
*ThirdItem*

??

Since I am using WriteLine, my guess is a new line is added after the last string and hence the last empty item in the array after splitting.

But why is there a new line in the beginning of the second and third strings?

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about string