/// <summary> /// Returns an updated file stream when last write date of the <paramref name="currentStream"/> /// has another day than today. In this case, the <paramref name="currentStream"/> is closed /// and its file is renamed. Finally, NULL is returned. /// When the <paramref name="currentStream"/> does not require an update, it is returned /// unmodified. /// </summary> protected virtual AbstractStreamWriter UpdateFileStream(AbstractStreamWriter currentStream) { // No stream, nothing to check if (currentStream == null) { return(null); } // When nothing has been written to the stream yet, there is nothing to check if (currentStream.lastWrite == default) { return(currentStream); } // When the day hasn't changed yet, there is nothing to do if (currentStream.lastWrite.Day == DateTime.Today.Day) { return(currentStream); } // Close stream DateTime lastWriteDay = currentStream.lastWrite; currentStream.Dispose(); // Calculate new file name string year = lastWriteDay.Year.ToString(); string month = lastWriteDay.Month.ToString("00"); string day = lastWriteDay.Day.ToString("00"); int extIdx = FileName.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase); string fnm = FileName.Substring(0, extIdx); string ext = FileName.Substring(extIdx); string mvFn = $"{fnm}-{year}-{month}-{day}{ext}"; // Renamed existing file File.Move(FileName, mvFn); // Drop existing file stream return(null); }
/// <inheritdoc /> protected override void Write(string value) { if (string.IsNullOrEmpty(FileName) || string.IsNullOrEmpty(value)) { return; } AbstractStreamWriter streamWriter = GetStreamWriter(); if (streamWriter == null) { return; } byte[] data = Encoding.UTF8.GetBytes(value); streamWriter.LockStream(); try { streamWriter.WriteToStream(data); } finally { streamWriter.UnlockStream(); } }
/// <summary> /// Returns a stream writer to write to. /// The instance is either newly created or an already existing /// one is returned. /// </summary> protected virtual AbstractStreamWriter GetStreamWriter() { if (DailyRolling) { _streamWriter = UpdateFileStream(_streamWriter); } if (_streamWriter != null) { return(_streamWriter); } if (LockingModel == ELockingModel.Exclusive) { _streamWriter = new ExclusiveLockingStreamWriter(); } else if (LockingModel == ELockingModel.Minimal) { _streamWriter = new MinimalLockingStreamWriter(); } else { _streamWriter = new NonLockingStreamWriter(); } string fqFilePath = Path.GetFullPath(FileName); string fqFolderPath = Path.GetDirectoryName(fqFilePath); if (!string.IsNullOrEmpty(fqFolderPath) && !Directory.Exists(fqFolderPath)) { Directory.CreateDirectory(fqFolderPath); } _streamWriter.InitStream(FileName, Append); return(_streamWriter); }
/// <inheritdoc /> protected override void OnDispose(bool disposing) { ReleaseUnmanagedResources(); _streamWriter?.Dispose(); _streamWriter = null; }