Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 575
Clinemi Avatar asked May 06 '11 14:05

Clinemi


3 Answers

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);
}
like image 64
Oleks Avatar answered Oct 21 '22 18:10

Oleks


You can

  • Read Attachment.ContentStream
  • If you now have a StreamReader or similar, use the BaseStream property to try and find the inner FileStream
  • Read FileStream.Name

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.

like image 23
Rup Avatar answered Oct 21 '22 20:10

Rup


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.

like image 30
Timbo Avatar answered Oct 21 '22 19:10

Timbo