Exemplo n.º 1
0
        static public void CleanupOldLogFiles(string logBaseFilename, int maxAgeOfLogsInDays)
        {
            // Launch a worker thread that will delete old log files in the background
            LogCleanupParams logCleanupParams = new LogCleanupParams(logBaseFilename, maxAgeOfLogsInDays);
            BackgroundWorker backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += new DoWorkEventHandler(CleanupOldLogFiles_DoWork);
            backgroundWorker.RunWorkerAsync(logCleanupParams);
        }
Exemplo n.º 2
0
        static private void CleanupOldLogFiles_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // Get the background worker that called this event.
                BackgroundWorker backgroundWorker = (sender as BackgroundWorker);

                // Get the parameters object from the argument
                LogCleanupParams logCleanupParams = (e.Argument as LogCleanupParams);

                // Extract folder and filename from the complete file path
                string logFileFolder   = Path.GetDirectoryName(logCleanupParams.LogFilename);
                string justLogFilename = Path.GetFileName(logCleanupParams.LogFilename);

                // Create folder if it doesn't exist already
                try
                {
                    if (!Directory.Exists(logFileFolder))
                    {
                        Directory.CreateDirectory(logFileFolder);
                    }
                }
                catch { }

                // We expect the log files to start with the naming convention of "yyyyMMdd_THHmmssZ"
                // If we are able to decode this prefix to a valid date, then delete the log file if
                // the date signifies that it is older than "maxAgeOfLogsInDays" days
                try
                {
                    string[] logFiles = Directory.GetFiles(logFileFolder, "*" + justLogFilename, SearchOption.TopDirectoryOnly);
                    foreach (string nextLogFile in logFiles)
                    {
                        try
                        {
                            string   justFilename     = Path.GetFileName(nextLogFile);
                            DateTime logFileTimeStamp = DateTime.SpecifyKind(System.Xml.XmlConvert.ToDateTime(justFilename.Substring(0, 17), "yyyyMMdd_THHmmssZ"), DateTimeKind.Utc);
                            if (logFileTimeStamp < DateTime.Today.AddDays(logCleanupParams.MaxAgeOfLogsInDays * (-1)))
                            {
                                File.Delete(nextLogFile);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                catch
                {
                }
            }
            catch { }
        }