0

The timer, email attachment sending work OK. However it is fails on file deletion. "The process cannot access the file x because it is being used by another process" I dont understand it. who is using the file? the file is sent and it is done. the deletion is after the email sent. why the error?

class Program
{
    static void Main(string[] args)
    {
        Timer aTimer = new Timer(10000);
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.Enabled = true;
        Console.WriteLine("Press the Enter key to exit the program.");
        Console.ReadLine();

    }

    private static void OnTimedEvent(object source, ElapsedEventArgs e )
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        string[] DirList = Directory.GetFiles(@"C:\dir_a");

        if (DirList.Length > 0)
        {
            foreach (string s in DirList)
            {
                try
                {
                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient("xx");
                    mail.From = new MailAddress("xx");
                    mail.To.Add("xx");
                    mail.Subject = "xx";
                    mail.Body = "xx";

                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(s);
                    mail.Attachments.Add(attachment);

                    SmtpServer.Port = 25;
                    SmtpServer.EnableSsl = false;

                    SmtpServer.Send(mail);
                    Console.WriteLine("email sent");

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }// end of foreach
            foreach (string s in DirList)
            {
                File.Delete(s);
            }

        }
John Ryann
  • 2,283
  • 11
  • 43
  • 60
  • 1
    http://stackoverflow.com/questions/877889/the-process-cannot-access-the-file-because-it-is-being-used-by-another-process – arunlalam May 10 '13 at 19:49

1 Answers1

8

You need to dispose the Attachment using a using statement.

Make sure to only dispose it after you send the email.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964