Nick,
It seems you are generating a temporary file which is attached to the
email, and then mailed.
What I would do here is that when creating the file, make a call to
CreateFile through the P/Invoke layer. When you call this, pass
FILE_ATTRIBUTE_TEMPORARY and FILE_FLAG_DELETE_ON_CLOSE.
FILE_ATTRIBUTE_TEMPORARY will prevent the file from being written to the
disk if sufficient cache memory is available. FILE_FLAG_DELETE_ON_CLOSE
will cause the file to be deleted when it is closed.
Once you have that, create your FileStream (passing the handle returned
from CreateFile), and pass that to the constructor for the Attachment that
you add to the email.
That way, once the file is sent, and you call dispose on the Message,
the file will be deleted automatically.
The reason this happens is for one of two reasons. First could be that
you are using the constructor for Attachment which is taking the filename as
a string. When this happens, it opens the file for read access, and only
allows read operations to be performed on the file while the stream is open.
The stream is still open when the event is fired.
The second could be that you are not setting the share mode on your
FileStream to the appropriate value when creating it. You could fix it on
this level, and then manually delete the file, but I think letting the OS do
it is better.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"Nick Z." <pa*****@gmail.com> wrote in message
news:Z2****************@fe09.lga...
When using SmtpClient and sending a message with an attached file using
SendAsync(...), if I add File.Delete(pathToAttachedFile) in the
SendCompleted event handler I get a file in use exception. Is there a way
to overcome this problem?
Thanks,
Nick Z.