将文件从 MemoryStream 附加到 C# 中的 MailMessage

Attach a file from MemoryStream to a MailMessage in C#(将文件从 MemoryStream 附加到 C# 中的 MailMessage)

本文介绍了将文件从 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

基础教程推荐