C# 从邮件附件中获取文件名
我有一个简单的 C# 应用程序,用于发送 SMTP 电子邮件(使用 System.Net.Mail 类)。发送(通过电子邮件发送)MailMessage 对象后,我想迭代附件列表并删除与这些附件关联的原始文件...但我很难找到与每个附件关联的完整文件路径 - 不保留我的自己的附件文件路径集合。必须有一种好方法从附件对象中提取完整的文件路径。
我知道这一定很简单,但我在这上面花了很多时间......是时候询问其他人了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您通过带有
filePath
参数的Attachment
构造函数添加附件,则可以通过ContentStream
属性检索这些附件,并且其类型为文件流
。以下是获取附加文件的文件名的方法:但不要忘记首先处理
MailMessage
对象,否则您将无法删除这些附件:If you adding your attachments through the
Attachment
constructor withfilePath
argument, these attachments can be retrieved throughContentStream
property and will be of typeFileStream
. Here is how you can get file names of the files attached:But don't forget to dispose
MailMessage
object first, otherwise you won't be able to delete these attachments:您可以
但请记住,邮件消息(以及附件及其流)可能不会立即收集或清理,因此您可能无法直接删除文件离开。如果您确实需要以这种方式执行操作,您可能会更好地对 Attachment 进行子类化,并记录文件名和子类 Dispose(在基本 dispose 之后执行)来执行删除。
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.