Hi,
In Application.StartupPath + @"\Test.txt" got
11111
2222
3333
Read them and print out:
string ss = System.IO.File.ReadAllText(Application.StartupPath + @"\Test.txt");
string[] items = ss.Split('\n');
foreach(string item in items)
Console.WriteLine(item);
Why got empty lines as follows:
11111
(empty line here)
2222
(empty line here)
3333
Loading
VulpesPosted Jan 5, 2014, 4:25 PM
The (unsatisfactory) answer is that all the overloads of the String.Split method which use a string as a separator require you to use a string array rather than just a (scalar) string:
http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
A curious design decision by the .NET framework team :(
However, you can use Regex.Split instead:
string[] items = System.Text.RegularExpressions.Regex.Split(ss, "\r\n");
VulpesPosted Jan 5, 2014, 5:47 PM
Although it doesn't appear to be documented, I think that Convert.ToInt32 (and to all other numeric types) also ignores leading and trailing (but not inner) white-space as well. However, to be on the safe side, you can always apply the Trim() method to the string before attempting to convert it.
DavePosted Jan 5, 2014, 4:56 PM
DavePosted Jan 5, 2014, 4:15 PM
VulpesPosted Jan 5, 2014, 3:53 PM
Notice the 0D byte before each 0A.
In Windows, the line terminator is \r\n which in hex bytes is 0D 0A or 13 10 in decimal.
So when you split on '\n', the first two items in the array will end with '\r'. Now, normally, printing '\r' (known as carriage return) to the console causes the cursor to jump back to the beginning of the current line and when I run the code myself there are no empty lines.
It therefore appears that, for some unknown reason, '\r' is generating a new line on your console rather than a carriage return.
As an experiment, you could try this code to see if a blank line appears:
Console.WriteLine("One\r");
Console.WriteLine("Two\r");
though the following code should get rid of them altogether:
DavePosted Jan 5, 2014, 3:37 PM
VulpesPosted Jan 5, 2014, 3:21 PM