简体   繁体   中英

C# Get filename from mail attachements

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM