user687459
user687459

Reputation: 163

Got wrong data while split file into arrays

I have file contains two lines and each line contains 200 fields and I would like to split it into arrays

using (StreamReader sr = File.OpenText(pathSensorsCalc))
{
     string s = String.Empty;
     while ((s = sr.ReadLine()) == null) { };
     String line1 = sr.ReadToEnd();
     String line2 = sr.ReadToEnd();
     CalcValue[0] = new String[200];
     CalcValue[1] = new String[200];
     CalcValue[0] = line1.Split(' ');
     CalcValue[1] = line2.Split(' ');
}

After the code above, CalcValue[1] is empty and CalcValue[0] contains data of the second line (instad of the first one). Any ideas?

Upvotes: 0

Views: 49

Answers (2)

Thomas
Thomas

Reputation: 203

When using

sr.ReadToEnd()

, you are reading to the end of your input stream. That means, after the first call of

String line1 = sr.ReadToEnd()

your stream is already at the last position. Replace your ReadToEnd() call with ReadLine() calls. That should work.

Upvotes: 2

Sweeper
Sweeper

Reputation: 270790

In the Windows OS, a new line is represented by \r\n. So you should not split the lines by spaces (" ").

Which means you should use another overload of the Split method - Split(char[], StringSplitOptions). The first argument is the characters you want to split by and the second is the options. Why do you need the options? Because if you split by 2 continuous characters you get an empty element.

So now it is easy to understand what this code does and why:

line1.Split (new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 0

Related Questions