4
I have a software that records error logs of itself inside a "logs" folder. Each log file is created with the current day date, so it is unique to the current day. Example: 30-04-2014.log.
I use StreamWriter
to log logs each time they occur. The program nay is a service, so it does not "turn day" running on the machine. Disregard that my StreamWriter
may be using 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 cannot 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)
Hence every hour I keep accumulating errors and old logs are not erased.
Any part of this code blocks files against access?
FileInfo
is the best way to access the dates of last access or written in the file?
EDITION:
I forgot to mention one detail: it is possible to delete (and any other operation) the files using explorer.
EDITION:
To log the errors, I call the following method within the 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);
}
post a summary of how you create . log, I believe the problem is in the create mode and not in the delete.
– Dorathoto