Problem with File IO and splitting strings with Environment.NewLine in VB.Net
- by Senthil
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?