Skip to content

9.2 Reading from a file

  1. If needed, start from the project up to chapter 8. This contains the classes as you left them at the end of chapter 8.
  2. Create a new folder in your project named Data.
  3. Create a file Rectangle.csv with the following content and place it in the Data folder:

    1
    2
    3
    4
    5
    3,3,0,7,red
    3,2,0,4,yellow
    5,2,0,2,green
    5,2,3,7,purple
    5,4,5,7,orange
    

    Format: length, width, x, y, color

  4. Add the following code to your Main method:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    List<Rectangle> rectangles = new List<Rectangle>();
    string filePath = "Data/Rectangle.csv";
    
    try
    {
        string[] lines = File.ReadAllLines(filePath);
        foreach (string line in lines)
        {
            string[] values = line.Split(',');
            double length = double.Parse(values[0]);
            double width = double.Parse(values[1]);
            double x = double.Parse(values[2]);
            double y = double.Parse(values[3]);
            rectangles.Add(new Rectangle(length, width, new Point(x, y), values[4]));
        }
    
        foreach (Rectangle rect in rectangles)
        {
            Console.WriteLine(rect);
            Console.WriteLine();
        }
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine("The file was not found.");
    }
    
    • File.ReadAllLines(filePath) can throw a FileNotFoundException. Therefore use a try/catch block.
    • Make sure the file is copied to the output directory: in the .csproj add <Content Include="Data\*.csv" CopyToOutputDirectory="PreserveNewest" /> or set "Copy to Output Directory" to "Copy if newer" in file properties.
  5. Run your program. You will see the information of five rectangles.