0

计时器、电子邮件附件发送工作正常。但是,文件删除失败。“该进程无法访问文件 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);
            }

        }
4

1 回答 1

8

您需要处理Attachmentusingusing语句。

确保仅在发送电子邮件后将其丢弃。

于 2013-05-10T19:48:32.247 回答