Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Amit Ghosh
Amit Ghosh
8,943 Points

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
38,047 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


 for (int j = 1; j < done.Length; j++)
 var newLine = string.Format("{0},{1},{2}", name[j], phone[j], faxnumber[j]);
            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.