0

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.

3
  • 3
    Attachements should be disposed too. Otherwise they keep the attachment locked Commented May 5, 2014 at 14:15
  • 1
    Don't check File.Exists() like that. Just call File.Delete() and handle the exception. Also, that catch block is meaningless. You can just remove it, and leave the try/finally by themselves. Commented May 5, 2014 at 16:09
  • Joel thanks for the suggestion i made the change as well. Commented May 6, 2014 at 5:37

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.