Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Streams and Data Processing Reading Data Reading a CSV File

Help in understanding the reader variable

Please refer to the below portion of the code while trying to read the files from the csv file: using (StreamReader reader = new StreamReader(filename)) { //reader.ReadLine(); string line = ""; while((line=reader.ReadLine())!=null) { string[] values = line.Split(','); gameresult.Add(values); } }

Keeping everything intact , if I alter Split method with string[] values = reader.Readline().Split(','); I face 2 problems: 1) in the last iteration when the while condition eventually returns a NULL, I will get a null exception. I understand that. 2) The portion I don't understand is instead of 180 rows , its returning me 90 rows. That means it calculating every 2 rows as 1 row.

Can someone please help me understand why this behavior. Also for in memory parsing like this, is it a best practice to initialize a string and loop with a while.

Thanks, Amit.

1 Answer

vincent batteast
vincent batteast
51,094 Points

I would use a different way This put it into one array of string

 String[] allLines = System.IO.File.ReadAllLines(location of the file);

check the lines

next maybe a for loop I would do whatever I need to do with the files

last

 for (int j = 1; j < done.Length; j++)
            {
 var newLine = string.Format("{0},{1},{2}", name[j], phone[j], faxnumber[j]);
                csv.AppendLine(newLine);
            }
            File.WriteAllText(were you want the new file, csv.ToString());

that put it back into a csv file and in the location you want it in.

I hope this help.