File.WriteAllBytes() 后无法删除文件

Not able to delete a file after File.WriteAllBytes()

我正在尝试将字节数组写入文件并将其作为电子邮件发送。之后我需要从保存的位置删除文件。

但是删除的时候报错

'The process cannot access the file 'file path' because it is being used by another process.'

根据File.WriteAllBytes() documentation,它创建一个新文件,将指定的字节数组写入文件,然后关闭文件。如果目标文件已经存在,则将其覆盖。请帮我找到解决办法。

string FolderPath = MyPath + "PaySlips";
string filePath = FolderPath + "/" + userID + "-PaySlip_" + ddlMonth.SelectedItem.Text + "_" + ddlYear.SelectedItem.Text + ".pdf";

if (!Directory.Exists(FolderPath))
{
  Directory.CreateDirectory(FolderPath);
}

File.WriteAllBytes(filePath, bytes);
                
ArrayList attachments = new ArrayList();
attachments.Add(filePath);
SendEmail(emailID, cc, attachments);

if (File.Exists(attachments[0].ToString())) {
  File.Delete(attachments[0].ToString()); //exception happens here
}

'''

您需要在“关闭”之后而不是之前删除文件。只要关闭尚未执行,文件就会处于流循环中,并且它算作自己的进程,因此在文件关闭之前无法删除。希望这可以帮助。我猜您的 close 语句在该代码下方。将它移到删除语句之前。

我得到了解决方案。谢谢@Cleptus File.WriteAllBytes() 已经关闭,在 SendMail() 中,它又被打开了。因此,通过处理这些对象,它起作用了

我的代码中的 SendEmail() 方法有

SmtpClient smC= new SmtpClient();
 MailMessage mM= new MailMessage();

我在 finally 块中添加了 SMTPClient 和 MailMessage 的处理

try
            {
                smC.Send(mM);

            }
            catch (Exception ex)
            {
                Err = ex.Message;
            }
            finally {
                mM.Dispose();
                smC.Dispose();
            }

string FolderPath = MyPath + "PaySlips"; string filePath = FolderPath + "/" + userID + "-PaySlip_" + ddlMonth.SelectedItem.Text + "_" + ddlYear.SelectedItem.Text + ".pdf";

 if (!Directory.Exists(FolderPath))
        {
            Directory.CreateDirectory(FolderPath);
        }

        

       File.WriteAllBytes(filePath, bytes);
             File.Close();
                File.Dispose();
                

                ArrayList attachments = new ArrayList();
                attachments.Add(filePath);
                SendEmail(emailID, cc, attachments);


   if (File.Exists(attachments[0].ToString())) {
            File.Delete(attachments[0].ToString()); 
        }