I have a simple C# app that send SMTP emails (using System.Net.Mail classes). After sending (emailing) a MailMessage object I want to iterate through the list of the attachments and delete the original files associated with those attachments... but I am having a hard time finding the full file path associated with each attachment - without keeping my own collection of attachment filepaths. There has got to be a good way to extract the full file path from the attachment object.
I know this has got to be simple, but I am spending way to much time on this..time to ask others.
If you adding your attachments through the Attachment
constructor with filePath
argument, these attachments can be retrieved through ContentStream
property and will be of type FileStream
. Here is how you can get file names of the files attached:
var fileNames = message.Attachments
.Select(a => a.ContentStream)
.OfType<FileStream>()
.Select(fs => fs.Name);
But don't forget to dispose MailMessage
object first, otherwise you won't be able to delete these attachments:
IEnumerable<string> attachments = null;
using (var message = new MailMessage())
{
...
attachments = message.Attachments
.Select(a => a.ContentStream)
.OfType<FileStream>()
.Select(fs => fs.Name);
}
foreach (var attachment in attachments )
{
File.Delete(attachment);
}
You can
but bear in mind that the mail message (and hence attachments and their streams) may not get collected or cleaned up immediately, so you may not be able to delete the file straight away. You might do better subclassing Attachment and both record the filename and subclass Dispose (to execute after the base dispose) to do the delete if you really do need to do things this way.
It's generally easiest to take a slightly different tack and attach via a memorystream rather than a file. That way you avoid all the issues around saving the files to disk and cleaning them up afterwards.
Short article here on that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With