草庐IT

c# - 电子邮件删除附件后,错误 "The process cannot access the file because it is being used by another process."

coder 2024-05-28 原文

我正在做一个电子邮件表单。电子邮件有附件,并在附加文件后发送电子邮件。接下来需要从服务器删除文件。当我试图获取文件时,它给了我主题错误。我什至在删除文件之前调用了 GC.Collect(),但错误仍然存​​在。我删除文件的代码是:

 private void DeleteFiles(DataTable dt)
{
    GC.Collect();
    String[] sAttachments = new String[dt.Rows.Count];
    try
    {

        sAttachments = new String[dt.Rows.Count];
        for (Int32 J = 0; J < dt.Rows.Count; J++)
        {
            sAttachments[J] = dt.Rows[J]["AttachmentExt"].ToString().Trim();
            string workDir = Server.MapPath(".") + @"\upload\";
            if (File.Exists(workDir + sAttachments[J]))
                File.Delete(workDir + sAttachments[J]);                
        }
    }
    catch (Exception ex)
    {

    }

要将文件附加到电子邮件,我的代码是:

 oMess.Subject = sSubject; 
        string workDir = System.Web.HttpContext.Current.Server.MapPath(".") + @"\upload\";
        if (Attachments != null)
        {
            for (Int32 I = 0; I < Attachments.Length; I++)
            {
                oatt = new Attachment(workDir+ sAttachments[I]);
                oMess.Attachments.Add(oatt);
            }
        }
        oMess.IsBodyHtml = IsHtml;
        oMess.Body = sBody;
       SendMessageGmail(oMess);

编辑:我的邮件发送代码是:

 private void SendMessageGmail(MailMessage message)        
    {
        SmtpClient client = new SmtpClient("smtp.gmail.com");
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        NetworkCredential loginInfo = new NetworkCredential("myid", "mypassword");
        client.Credentials = loginInfo;
        client.Port = 587;
        client.Send(message);
    }

请指导和帮助。谢谢

最佳答案

使用这个。它对我有用

client.Send(oMess);
oMess.Attachments.Dispose();

这个我试过了,但是没用

client.Send(oMess);
oMess.Dispose();

关于c# - 电子邮件删除附件后,错误 "The process cannot access the file because it is being used by another process.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5819810/

有关c# - 电子邮件删除附件后,错误 "The process cannot access the file because it is being used by another process."的更多相关文章

随机推荐