File supposedly being used cannot be deleted

Asked

Viewed 5,206 times

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.

2 answers

2

Wow, I figured out the problem! It was my fault, because I did not mention that before deleting the old logs, I check if there are logs bigger than 2KB (which means there were many errors that day), to send them by email.

The problem came precisely from sending the logs, because I did not know that I should discard (Dispose) the object I created with the class System.Net.Mail.MailMessage. After I just put it all in the using, the entire program worked properly and the files were no longer in use "mysteriously".

Before:

private EnviarEmail()
{
  MailMessage mail = new MailMessage()
  {
    //...
  }
}

Afterward:

private EnviarEmail()
{
  using (MailMessage mail = new MailMessage())
  {
    //...
  }
}

I hope my mistake was helpful.

1

Check that your method that creates the log files is creating them with access permission and if when placing the pointer at the beginning of the file in the creation you also need to close.

   StreamWriter sw = new StreamReader(fs);
   //Algum código aqui
   sw.Close();

Once you do not close it the file is open soon in use.

  • 2

    In this example, the exact opposite can happen. If there is an exception, the file will not be closed.

  • Yes, I close Streamwriter at the end of each error report. The big question is: there are logs of other days that the program claims to be being used. This sounds like a joke to me, since no part of my code writes or reads anything from previous days, with the exception of Fileinfo, which, the way I used, was not to block any file.

  • 1

    It would have been better with a using: using (StreamWriter sw = new StreamReader(fs)) { /* código aqui */ }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.