Nikitesh
Nikitesh

Reputation: 1305

File is being used by another process while deleting the file

I have function to create a pdf and then send it to through mail in attachments.

The function to create pdf:

public string CreatePdf()
        {

            try
            {
                using (document = new Document())
                {

                    if (File.Exists(filePath))
                    {
                        workStream.Dispose();
                        File.Delete(filePath);
                    }
                // LOGIC to Create PDF
                    return filePath;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                document.Close();
                document.Dispose();
                workStream.Close();
            }
        }

To add to attachments:

myMail.attachment = new Attachment(new CreatePdf());

When i create file for the first time it is created fine, but when i try to create pdf again i get the following error on File.Delete(filePath)

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

I saw other similar questions but couldn't figure out what needs to be closed exactly as i have closed everything.

Upvotes: 0

Views: 971

Answers (2)

Nikitesh
Nikitesh

Reputation: 1305

Thanks to Steve and Lynx got it solved don't know whether it is the right way. Attachments class is IDisposable so i thought it will dispose the stream on its own. i just added attachments.dispose().

Upvotes: 0

Lynx
Lynx

Reputation: 506

I don't see anything wrong with the code you provided. I personally think that you are not closing or disposing something like the attachment. Why don't you try implementing your attachment with a using statement?

Upvotes: 1

Related Questions