问题描述
我正在编写一个将文件附加到电子邮件的程序.目前我正在使用 FileStream 将文件保存到磁盘中,然后我使用
I am writing a program to attach a file to email. Currently I am saving file using FileStream into disk, and then I use
System.Net.Mail.MailMessage.Attachments.Add(
new System.Net.Mail.Attachment("file name"));
我不想将文件存储在磁盘中,我想将文件存储在内存中,然后从内存流中将其传递给 Attachment.
I do not want to store file in disk, I want to store file in memory and from memory stream pass this to Attachment.
推荐答案
这里是示例代码.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write("Hello its my sample file");
writer.Flush();
writer.Dispose();
ms.Position = 0;
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.txt";
// I guess you know how to send email with an attachment
// after sending email
ms.Close();
编辑 1
您可以通过 System.Net.Mime.MimeTypeNames 指定其他文件类型,例如 System.Net.Mime.MediaTypeNames.Application.Pdf
You can specify other file types by System.Net.Mime.MimeTypeNames like System.Net.Mime.MediaTypeNames.Application.Pdf
根据 Mime 类型,您需要在 FileName 中指定正确的扩展名,例如 "myFile.pdf"
Based on Mime Type you need to specify correct extension in FileName for instance "myFile.pdf"
这篇关于将文件从 MemoryStream 附加到 C# 中的 MailMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)