C# Get filename from mail attachements

好久不见. 提交于 2019-12-10 03:10:37

问题


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.


回答1:


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.




回答2:


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);
}



回答3:


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.



来源:https://stackoverflow.com/questions/5912649/c-sharp-get-filename-from-mail-attachements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!