after email deleting attachment file, error “The process cannot access the file because it is being used by another process.”

前端 未结 7 638
逝去的感伤
逝去的感伤 2021-01-01 23:48

I am doing an email form. Email has attachments and after attaching files email is sent. Next there is requirement to delete file from server. When I tried to get the file i

相关标签:
7条回答
  • 2021-01-02 00:25

    This worked for me:

    FileStream file = new FileStream(attachment, FileMode.Open, FileAccess.Read);
    MemoryStream ms = new MemoryStream();
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    ms.Write(bytes, 0, (int)file.Length);
    
    objEmail.Attachments.Add(new Attachment(ms, new FileInfo(attachment).Name));
    
    file.Close();
    ms.Close();
    System.GC.Collect();
    System.GC.WaitForPendingFinalizers();
    System.IO.File.Delete(attachment);
    
    0 讨论(0)
提交回复
热议问题