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
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
