private StreamWriter OpenFileForWriting(
            string folderPath,
            SizeLimitedLogFileDescription logFileDescription,
            Encoding encoding)
        {
            EnsureDirectoryCreated(folderPath);
            try
            {
                var fullPath = Path.Combine(folderPath, logFileDescription.FileName);
                var stream   = File.Open(fullPath, FileMode.Append, FileAccess.Write, FileShare.Read);

                return(new StreamWriter(stream, encoding ?? Encoding.UTF8));
            }
            catch (IOException ex)
            {
                // Unfortuantely the exception doesn't have a code to check so need to check the message instead
                if (!ex.Message.StartsWith("The process cannot access the file"))
                {
                    throw;
                }
            }
            catch (UnauthorizedAccessException)
            {
                if (exceptionAlreadyThrown)
                {
                    throw;
                }

                exceptionAlreadyThrown = true;
            }

            return(OpenFileForWriting(folderPath, logFileDescription.Next(), encoding));
        }
        private SizeLimitedFileSink NextSizeLimitedFileSink()
        {
            SizeLimitedLogFileDescription next = this.currentSink.LogFileDescription.Next();

            this.currentSink.Dispose();

            return(new SizeLimitedFileSink(this.formatter, this.logDirectory, next, this.encoding));
        }
 internal SizeLimitedFileSink(
     ITextFormatter formatter,
     SizeLimitedLogFileDescription sizeLimitedLogFileDescription,
     StreamWriter writer)
 {
     this.formatter = formatter;
     this.sizeLimitedLogFileDescription = sizeLimitedLogFileDescription;
     this.output = writer;
 }
 public SizeLimitedFileSink(
     ITextFormatter formatter,
     string logDirectory,
     SizeLimitedLogFileDescription sizeLimitedLogFileDescription,
     Encoding encoding = null)
 {
     this.formatter = formatter;
     this.sizeLimitedLogFileDescription = sizeLimitedLogFileDescription;
     this.output = OpenFileForWriting(logDirectory, sizeLimitedLogFileDescription, encoding ?? Encoding.UTF8);
 }