I have software that logs logs of errors from it even inside a "logs" folder. Each log file is created with the date of the current day, and is therefore unique to the current day. Example: 30-04-2014.log .
I use StreamWriter
to log the logs each time they occur. The no program is a service, so it does not "turn around" by running the machine. Disregard that my StreamWriter
may be using the files from previous days (which I wish to delete).
The program has a timer that runs the following method every 1 hour to delete my logs from previous days:
public static void LimparLogsAntigos()
{
//Suponha que eu tenha permissão total para gravar em "C:\logs".
string[] files = Directory.GetFiles("C:\logs", "*.log", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.LastWriteTime.DayOfYear <= DateTime.Now.AddDays(-1).DayOfYear) //Apagar somente logs do dia anterior.
{
fi.Delete();
}
}
}
Using this code, I get the following message:
System.IO.IOException: The process can not access the file 'C: \ logs \ 23-04-2014.log' because it is being used by another process. in System.IO .__ Error.WinIOError (Int32 errorCode, String maybeFullPath)
Then every hour I get accumulated errors and the old logs are not deleted.
Does any part of this code block files against access?
FileInfo
is the best way to access the last access or write dates in the file?
EDITION:
I forgot to mention a detail: you can delete (and any other operation) the files using explorer.
EDITION:
To log the errors, I call the following method within catch
:
public static void RegErro(string msgErro) //recebe a mensagem de erro a ser registrada no log.
{
StreamWriter sw = new StreamWriter(logsFolder + "\" + logName, true, Encoding.UTF8);
sw.Write(msgErro);
sw.Close();
File.SetAttributes(logsFolder + "\" + logName, FileAttributes.Normal | FileAttributes.NotContentIndexed);
}