I have a C# WPF application where I save logs as a text file.
The log is saved as YYYY-MM-DD HH:MM LogContent
format.
I was able to read the first line of the log file and compare the date to see if it is more than 2 weeks old using code below.
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string logFileName = @"MyLog.log";
public void CleanupTimeLog()
{
string getDate = File.ReadLines(filePath + logFileName).First();
DateTime loggedTime = DateTime.Parse(getDate.Substring(0, 10));
if (loggedTime.AddDays(13) < DateTime.Now.Date)
{
// delete the line
}
}
Deleting multiple lines using foreach
seems very inefficient. How do I achieve my goal the simplest way possible?
I have checked some examples of deleting lines from text files, but I still cannot figure out how to delete them by dates.