2013-05-10 64 views
0

定時器,電子郵件附件發送工作正常。但是它在文件刪除時失敗。 「進程無法訪問文件x,因爲它正在被另一個進程使用」我不理解它。誰在使用該文件?該文件被髮送並完成。刪除是在電子郵件發送後。爲什麼錯誤?C#定時器和文件刪除

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); 
      } 

     } 
+1

http://stackoverflow.com/questions/877889/the-process-cannot-access-the-file-because-it-is-being-used-by-other-process – arunlalam 2013-05-10 19:49:56

回答

8

你需要使用using語句來處置Attachment

請務必在發送電子郵件後處置它。

+0

你能舉個例子嗎? – 2013-05-10 19:49:28

+0

...以及MailMessage和SmtpClient都實現了IDisposable。 – 2013-05-10 19:49:40

+1

@JohnRyann:http://msdn.microsoft.com/en-us/library/yh598w02.aspx – SLaks 2013-05-10 19:50:02