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