Beispiel #1
0
        /// <summary>
        /// Prepares a new file to write to.
        /// </summary>
        private void PrepareNewFile()
        {
            lock (FileSwitchLock)
            {
                string       fileBaseName = LogFileFolder.FullName + LogFilePrefix + DateTime.Now.ToString("yyyy-MM-dd");
                const string fileSuffix   = ".txt";
                CurrentLogFile = fileBaseName + fileSuffix;

                var oldFiles = LogFileFolder.GetFiles().Where(x => x.Name.StartsWith(LogFilePrefix)).ToList();
                if (oldFiles.Exists(x => x.FullName == CurrentLogFile))
                {
                    CurrentLogFile = fileBaseName + "_" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + fileSuffix;
                }

                if (oldFiles.Count >= MaxIterations)
                {
                    var earliesttFile = oldFiles.First(x => x.CreationTime == oldFiles.Min(c => c.CreationTime));
                    try
                    {
                        earliesttFile.Delete();
                    }
                    catch (IOException)
                    {
                    }
                    catch (UnauthorizedAccessException) when(!File.Exists(earliesttFile.FullName))
                    {
                        //Eat if file does not exist.
                    }
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Checks if a new file should be created or we a have an old one to write to. Deletes oldest file if <see cref="MaxIterations"/> is reached.
        /// </summary>
        private void ChooseFile()
        {
            var  oldFiles      = LogFileFolder.GetFiles().Where(x => x.Name.StartsWith(LogFilePrefix)).ToList();
            bool createNewFile = true;

            if (oldFiles.Count > 0)
            {
                createNewFile = false;
                var latestFile = oldFiles.First(x => x.CreationTime == oldFiles.Max(c => c.CreationTime));
                if (((DateTime.Now - latestFile.CreationTime).TotalDays > DaysBeforeNewFile) || latestFile.Length >= MaxFileSize)
                {
                    createNewFile = true;
                }
                else
                {
                    CurrentLogFile = latestFile.FullName;
                }
            }
            if (createNewFile)
            {
                PrepareNewFile();
            }
        }