【问题标题】:C# Timer and File deleteC# 定时器和文件删除
【发布时间】:2013-05-10 19:46:58
【问题描述】:

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

        }

【问题讨论】:

标签: c# file email


【解决方案1】:

您需要使用using 语句来处理Attachment

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

【讨论】:

  • ... 以及 MailMessage 和 SmtpClient 都实现了 IDisposable。
  • @AustinSalonen SmtpClient 无法处理
  • @JohnRyann: Yes it can.
  • @AustinSalonen:这对 .Net 4 来说是新的。
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多