ScrewTurn.Wiki.SettingsStorageProvider.CutLog C# (CSharp) Method

CutLog() private method

Reduces the size of the Log to the specified size (or less).
private CutLog ( int size ) : void
size int The size to shrink the log to (in bytes).
return void
        private void CutLog(int size)
        {
            lock(this) {
                // Contains the log messages from oldest to newest, and reverse the list
                List<LogEntry> entries = new List<LogEntry>(GetLogEntries());
                entries.Reverse();

                FileInfo fi = new FileInfo(GetFullPath(LogFile));
                int difference = (int)(fi.Length - size);
                int removeEntries = difference / EstimatedLogEntrySize * 2; // Double the number of removed entries in order to reduce the # of times Cut is needed
                int preserve = entries.Count - removeEntries; // The number of entries to be preserved

                // Copy the entries to preserve in a temp list
                List<LogEntry> toStore = new List<LogEntry>();
                for(int i = 0; i < preserve; i++) {
                    toStore.Add(entries[i]);
                }

                toStore.Sort((a, b) => a.DateTime.CompareTo(b.DateTime));

                StringBuilder sb = new StringBuilder();
                // Type | DateTime | Message | User
                foreach(LogEntry e in toStore) {
                    sb.Append(EntryTypeToString(e.EntryType));
                    sb.Append("|");
                    sb.Append(e.DateTime.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss"));
                    sb.Append("|");
                    sb.Append(e.Message);
                    sb.Append("|");
                    sb.Append(e.User);
                    sb.Append("\r\n");
                }

                FileStream fs = null;
                try {
                    fs = new FileStream(GetFullPath(LogFile), FileMode.Create, FileAccess.Write, FileShare.None);
                }
                catch(Exception ex) {
                    throw new IOException("Unable to open the file: " + LogFile, ex);
                }

                StreamWriter sw = new StreamWriter(fs, System.Text.UTF8Encoding.UTF8);
                // Type | DateTime | Message | User
                try {
                    sw.Write(sb.ToString());
                }
                catch { }
                sw.Close();
            }
        }