Home > Software engineering >  Not able to delete a file after File.WriteAllBytes()
Not able to delete a file after File.WriteAllBytes()

Time:12-22

I am trying to write byte array to a file and sending it as email. After that I need to delete the file from the saved location. But while deleting it throws error 'The process cannot access the file 'file path' because it is being used by another process.' As per the File.WriteAllBytes() documentation,it Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten. Pls help me to find a solution.

  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
        }

'''

CodePudding user response:

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()); 
        }

CodePudding user response:

I got the solution. Thanks @Cleptus

The SendEmail() method in my code has

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

I added dispose of SMTPClient and MailMessage in finally block

try
            {
                smC.Send(mM);

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

CodePudding user response:

you need to delete the file after "close" not before. As long as the close has not executed, the file will be in the stream loop and it counts as its own process and thus cannot be deleted until the file is closed. Hope this helps. Im guessing your close statement is below that code. Move it before the delete statment.

  • Related