Skip to content

9.3 Writing to a file

  1. Remove the following code from your Main method:

    1
    2
    3
    4
    5
    foreach (Rectangle rect in rectangles)
    {
        Console.WriteLine(rect);
        Console.WriteLine();
    }
    
  2. Add the following code to your Main method:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    string outputPath = "Data/Rectangles.txt";
    try
    {
        using (StreamWriter writer = new StreamWriter(outputPath))
        {
            foreach (Rectangle rect in rectangles)
            {
                writer.WriteLine(rect);
                writer.WriteLine();
            }
        }
    }
    catch (IOException)
    {
        Console.WriteLine("The file could not be created.");
    }
    

    Note: It is essential to properly close or dispose of the StreamWriter (the using statement does this automatically). Otherwise the data may not be written to the file.