Note that there are some explanatory texts on larger screens.

plurals
  1. POProblem with File IO and splitting strings with Environment.NewLine in VB.Net
    text
    copied!<p>I was experimenting with basic VB.Net File IO and String splitting. I encountered this problem. I don't know whether it has something to do with the File IO or String splitting.</p> <p>I am writing text to a file like so</p> <pre><code>Dim sWriter As New StreamWriter("Data.txt") sWriter.WriteLine("FirstItem") sWriter.WriteLine("SecondItem") sWriter.WriteLine("ThirdItem") sWriter.Close() </code></pre> <p>Then, I am reading the text from the file</p> <pre><code>Dim sReader As New StreamReader("Data.txt") Dim fileContents As String = sReader.ReadToEnd() sReader.Close() </code></pre> <p>Now, I am splitting <code>fileContents</code> using <code>Environment.NewLine</code> as the delimiter.</p> <pre><code>Dim tempStr() As String = fileContents.Split(Environment.NewLine) </code></pre> <p>When I print the resulting Array, I get some weird results</p> <pre><code>For Each str As String In tempStr Console.WriteLine("*" + str + "*") Next </code></pre> <p>I added the *s to the beginning and end of the Array items during printing, to find out what is going on. Since <code>NewLine</code> is used as the delimiter, I expected the strings in the Array to NOT have any NewLine's. But the output was this - </p> <pre><code>*FirstItem* * SecondItem* * ThirdItem* * * </code></pre> <p>Shouldn't it be this - </p> <pre><code>*FirstItem* *SecondItem* *ThirdItem* ** </code></pre> <p>??</p> <p>Why is there a new line in the beginning of all but the first string?</p> <p><strong>Update:</strong> I did a character by character print of <code>fileContents</code> and got this - </p> <pre><code>F - 70 i - 105 r - 114 s - 115 t - 116 I - 73 t - 116 e - 101 m - 109 - 13 - 10 S - 83 e - 101 c - 99 o - 111 n - 110 d - 100 I - 73 t - 116 e - 101 m - 109 - 13 - 10 T - 84 h - 104 i - 105 r - 114 d - 100 I - 73 t - 116 e - 101 m - 109 - 13 - 10 </code></pre> <p>It seems 'Environment.NewLine' consists of </p> <pre><code> - 13 - 10 </code></pre> <p>13 and 10.. I understand. But the empty space in between? I don't know whether it is coming due to printing to the console or is really a part of <code>NewLine</code>.</p> <p>So, when splitting, only the character equivalent of ASCII value 13, which is the first character of <code>NewLine</code>, is used as delimiter (as explained in the replies) and the remaining stuff is still present in the strings. For some reason, the mysterious empty space in the list above and ASCII value 10 together result in a new line being printed. </p> <p>Now it is clear. Thanks for the help. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload