0

我通过 .net 的 smtp 发送文件,如下所示:

private void SendMail()
{
  var _msg = new MailMessage();
  const string cEmailUsername = "xxxxxx";
  const string cEmailPassword = "zzzzzz";
  const string cSmtpClient = "yyyyyyy";

  try
  {
    using (var smtp = new SmtpClient(cSmtpClient))
    {
      _msg.From = string.IsNullOrEmpty(Configuration.CompanyEmailAddress)
                    ? new MailAddress(cEmailUsername)
                    : new MailAddress(Configuration.CompanyEmailAddress.ToLower());
      _msg.Subject = string.Format("Request for .Net Support - {0} - {1}", Configuration.CompanyID,
                                   Configuration.GetCompanyName());
      _msg.Body = string.Format("Propane.exe date: {0}{1}{1}{2}", Configuration.VersionDate, Environment.NewLine,
                                "Check parsing log file attached.");
      _msg.To.Add("eric@suburbansoftware.com");
      _msg.Attachments.Add(new Attachment(_logFile));

      var cred2 = new NetworkCredential(cEmailUsername, cEmailPassword);
      smtp.Port = 587;
      smtp.Credentials = cred2;
      smtp.Timeout = 0;
      smtp.Send(_msg);
    }

    var oldfile = _logFile + ".old";
    if (File.Exists(oldfile))
    {
      File.Delete(oldfile);
    }
    File.Move(_logFile,oldfile);
  }
  catch (Exception ex)
  {
    richTextBox_Message.Text += ex.Message;
  }
}

当我到达 file.move 时,我得到一个正在使用的文件异常。如果我注释掉使用部分,则移动工作正常。

有没有办法解决这个问题还是我做错了?

4

1 回答 1

2

Using仅适用于smtp,不适用于_msg。此变量是包含附件的变量,未处理。在完成using部分后立即包含此代码,一切都应该没问题:

_msg.Dispose();
_msg = null;
于 2013-08-07T16:38:49.910 回答