Attach a file from MemoryStream to a MailMessage in C#(将文件从 MemoryStream 附加到 C# 中的 MailMessage)
问题描述
我正在编写一个将文件附加到电子邮件的程序.目前我正在使用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将文件从 MemoryStream 附加到 C# 中的 MailMessage


基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01