C#定时器和文件删除

时间:2013-05-10 19:46:59

标签: c# file email

计时器,电子邮件附件发送工作正常。但是文件删除失败。 “该进程无法访问文件x,因为它正被另一个进程使用”我不明白。谁在使用该文件?文件已发送并完成。删除是在发送电子邮件之后。为什么错误?

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 个答案:

答案 0 :(得分:8)

您需要使用Attachment声明处理using

请务必在发送电子邮件后将其丢弃。