Michael's solution doesn't quite fulfill the requirements, which are to retry a fixed number of times, throwing the last failure.
For this, I would recommend a simple for loop, counting down. If you succeed, exit with break (or, if convenient, return). Otherwise, let the catch check to see if the index is down to 0. If so, rethrow instead of logging or ignoring.
public void Write(string body, bool retryOnError)
{
for (int tries = MaxRetries; tries >= 0; tries--)
{
try
{
_outputfile.Write(body);
_outputfile.Flush();
break;
}
catch (Exception)
{
if (tries == 0)
throw;
_outputfile.Close();
_outputfile = new StreamWriter(_filepath, true);
}
}
}
In the example above, a return would have been fine, but I wanted to show the general case.