C # Get file name from email applications

I have a simple C # application that sends SMTP emails (using the System.Net.Mail classes). After sending (sending via e-mail) the MailMessage object, I want to iterate over the list of attachments and delete the source files associated with these attachments ... but I find it difficult to find the full file path associated with each attachment - without saving my own set of file attachment paths . There should be a good way to extract the full file path from the attachment object.

I know this should be simple, but I spend a lot of time at this time to ask others.

+7
c # email filenames attachment
May 6 '11 at 14:11
source share
3 answers

You can

but keep in mind that the mail message (and therefore the attachments and their flows) cannot be immediately collected or cleaned, so you cannot immediately delete the file. You could improve the subclass of Attachment and both write the file name and the Dispose subclass (run after the dispose base) to do the deletion if you really need to do something this way.

+2
May 6 '11 at 14:37
source share

If you add your attachments through the Attachment constructor with the filePath argument, these attachments can be obtained through the ContentStream property and will be of the FileStream type. Here's how you can get attachment file names:

 var fileNames = message.Attachments .Select(a => a.ContentStream) .OfType<FileStream>() .Select(fs => fs.Name); 

But remember to delete the MailMessage object MailMessage , otherwise you cannot 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); } 
+6
May 6 '11 at 14:39
source share

As a rule, the easiest way is to use a slightly different checkmark and attach it via memystream, rather than a file. Thus, you avoid all the problems associated with saving files to disk and their subsequent cleaning.

A short article is here.

+1
May 6 '11 at 14:21
source share



All Articles