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 に到達すると、ファイル使用中の例外が発生します。using 部分をコメントアウトすると、移動は問題なく機能します。

これを回避する方法はありますか、それとも間違っていますか?

4

1 に答える 1

2

Usingsmtpではなく、だけで動作し_msgます。この変数は添付ファイルを含む変数であり、破棄されません。パーツを完成させた直後にこのコードを含めるusingと、すべてがうまくいくはずです:

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