In the example below, data from a source stream is written to a file specified by the string "filename". If a "not enough space on the disk" IOException occurs while writing, the file specified by the string "uselessFile" will be deleted to free up space and the write will be retried.
using System; using System.IO; using BetterStreams; namespace BetterStreamsExamples { static class ExceptionExample { public static void Write(string filename, Stream source, string uselessFile) { AsyncStream asyncStream = new AsyncStream ( File.OpenWrite(filename), AsyncStreamMode.Writing, 102400 //100KB buffer ); int readBytes=0; byte[] buffer = new byte[4096]; bool retry = false; while ( retry || (readBytes=source.Read(buffer,0,buffer.Length)) > 0) { retry = false; try { asyncStream.Write(buffer, 0, readBytes); } catch (AsynchronousBaseStreamException e) { //if we're out of space, try deleting //the useless file and continuing. if (e.InnerException is IOException && e.InnerException.Message.Contains("not enough space on the disk") && File.Exists(uselessFile)) { File.Delete(uselessFile); //retry writing the same data retry = true; continue; } else { asyncStream.Close(); throw e; //we can't recover } } } asyncStream.Close(); } } } |