/// <summary>
/// Write the monthly results to a data file in CSV format.
/// </summary>
/// <returns>0 if successful; -ve for error code</returns>
protected int WriteMonthlyResults()
{
OpenTemp.WriteLine(string.Format(”Writing the monthly results file ‘{0}’…”, _outputMonthlyFile));
// Open the file
StreamWriter sw;
try
{
sw = new StreamWriter(_outputMonthlyFile, false); // Overwrite (do not append)
OpenTemp.WriteLine(” File opened for writing”);
}
catch (Exception ex)
{
OpenTemp.WriteLine(string.Format(” Exception thrown when opening file: {0}”, ex.ToString()));
return -1;
}
if (sw == null)
{
OpenTemp.WriteLine(” Failed to open file (check that it exists and the path is correct)”);
return -2;
}
// Write header
sw.Write(”YEAR,MONTH,AVG”);
sw.WriteLine();
// Write one line at a time
int nMonths = 0;
foreach (KeyValuePair<DateTime, float> average in _monthlyAverages)
{
sw.WriteLine(string.Format(”{0}, {1}, {2}”, average.Key.Year, average.Key.Month, average.Value.ToString(”F2″)));
nMonths++;
}
// Done
sw.Close();
// Done
OpenTemp.WriteLine(string.Format(” Writing finished: {0} months written”, nMonths));
return 0;
}