Pardon my newness to the MailMessage and SmtpClient classes. I've built something that basically works, but in preparing to send the attachments, I sometimes copy the attachments to the temporary files location (Path.GetTempPath() + @"\" + timestampWithFF
), because they sometimes must be zipped to send. When this happens, I want to make sure I delete the files there after sending (especially because anything there is going to be relatively large).
Two-fold question:
1. should I not bother with cleaning up the files because the OS (win7) will do a good job of it?
2. how can I get the HDD location of the Attachments in client.SendCompleted
?
client.SendCompleted += (s, e) =>
{
client.Dispose();
foreach(Attachment a in msg.Attachments)
{
// want to actually delete the file from the HDD if it's in Path.GetTempPath();
}
msg.Dispose();
};
I see I could use a.Dispose()
, but I don't have any idea what it does...I suspect it's disposing of the object (which msg.Dispose
would do next anyways), but would leave the files on the HDD.
must I send the filepaths of the attachments separately?
the client.SendCompleted()
line is in:
sendMailAsync(SmtpClient client, MailMessage msg)
method. I could change this to:
sendMailAsync(SmtpClient client, MailMessage msg, List<string> attachments)
and add this to the SendCompleted()
, but it feels kinda clunky:
string tempDir = Path.GetTempPath();
foreach(string f in attachments)
{
if(f.Contains(tempDir)) // want to actually delete the file from the HDD if it's in Path.GetTempPath();
{
if (File.Exists(f)) { File.Delete(f); }
}
}
- should I not bother with cleaning up the files because the OS (win7) will do a good job of it?
If i were you, I would still delete the temp file, though OS would clean it, when it deems necessary
- how can I get the HDD location of the Attachments in client.SendCompleted?
The files in the attachments can be retrieved through ContentStream
. Their type would be of FileStream
.
client.SendCompleted += (s, e) =>
{
client.Dispose();
var fileattachments = msg.Attachments
.Select(x => x.ContentStream)
.OfType<FileStream>()
.Select(fs => fs.Name)
.ToArray();
msg.Dispose();
string tempPath = Path.GetTempPath();
foreach (var attachment in fileattachments )
{
if(attachment.Contains(tempPath)
{
File.Delete(attachment);
}
}
};
Note: First dispose the msg
object and then do the deletion