9.3 Writing to a file
-
Remove the following code from your
Mainmethod:1 2 3 4 5
foreach (Rectangle rect in rectangles) { Console.WriteLine(rect); Console.WriteLine(); } -
Add the following code to your
Mainmethod: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(theusingstatement does this automatically). Otherwise the data may not be written to the file.