6
Answers

Quick C# Help Retrieve data using while (!sr.EndOfStream)

David Chen

David Chen

14y
6k
1
I ran into problem for my school assignment and it is to display whatever in a meal.csv file, here is a code we are starting with. The array string of itemDetails is where the data is store then passed into array ReadLines, then in Main, it is passed to mealContent, but when I tried Console.WriteLine(mealContent); it only prompted System.String[]. So how do I at least display it out in the command prompt. Thanks for the help guys~ Source code is also attached

Code/meal.csv
lunch,bento box b - sashimi,box combo,$9.59
dinner,vegetable sushi,6 rolls,$3.50
dinner,tuna roll,3 rolls,$4.50
dinner,roe, 2 rolls,$3.95
lunch,bento box a - chicken teriyaki,box combo,$8.59

FileIOManager/FileLocation.cs

using
System;

namespace FileIOManager
{

    static
class FileLocation
    {
        public const string INPUT_FILE = "../../Data/meals.csv";
    }
}

FileIOManager/FileReader.cs

using
System;
using
System.IO;

namespace FileIOManager
{

    static public class FileReader
    {
        private static int GetLineCount()
        {

             StreamReader sr = new StreamReader(FileLocation.INPUT_FILE);
             int counter = 0;
             while (!sr.EndOfStream)
             {
                  counter++;
                  sr.ReadLine();
             }
             sr.Close();
             return counter;
         }
        

     public static string[] ReadLines()

     {

          int totalItems  = GetLineCount();

          string[] itemDetails = new string[totalItems];

          StreamReader sr = new StreamReader(FileLocation.INPUT_FILE);

 

          string itemDetail;

          int counter = 0;

 

            while (!sr.EndOfStream){

                itemDetail = sr.ReadLine();

                if (itemDetail.Trim() != "")

                    itemDetails[counter++] = itemDetail;

            }

            sr.Close();

            return itemDetails;

        }

    }

}

Attachment: help.zip

Answers (6)