c# - 如何获取System.Net.Mail.Attachment的内容

标签 c# email-attachments

我有一个 System.Net.Mail.Attachment 对象,其中包含一些 .csv 数据。我需要将附件的内容保存在一个文件中。我试过这个:

        var sb = new StringBuilder();
        sb.AppendLine("Accounts,JOB,Usage Count");


            sb.AppendLine("One,Two,Three");
            sb.AppendLine("One,Two,Three");
            sb.AppendLine("One,Two,Three");

        var stream = new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()));
        //Add a new attachment to the E-mail message, using the correct MIME type
        var attachment = new Attachment(stream, new ContentType("text/csv"))
        {
            Name = "theAttachment.csv"
        };


            var sr = new StreamWriter(@"C:\Blah\Look.csv");
            sr.WriteLine(attachment.ContentStream.ToString());
            sr.Close();

但该文件只有以下内容:“System.IO.MemoryStream”。 你能告诉我如何才能在那里获得真实数据吗?

谢谢。

最佳答案

您不能在任意流上调用 ToString。相反,您应该使用 CopyTo:

using (var fs = new FileStream(@"C:\temp\Look.csv", FileMode.Create))
{
    attachment.ContentStream.CopyTo(fs);
}

用它来替换示例的最后三行。默认情况下,ToString 只返回该类型的名称,除非该类重写了 ToString。 ContentStream 只是抽象 Stream(在运行时它是一个 MemoryStream),所以只有默认实现。

CopyTo 是 .NET Framework 4 中的新功能。如果您没有使用 .NET Framework 4,您可以使用扩展方法模拟它:

public static void CopyTo(this Stream fromStream, Stream toStream)
{
    if (fromStream == null)
        throw new ArgumentNullException("fromStream");
    if (toStream == null)
        throw new ArgumentNullException("toStream");

    var bytes = new byte[8092];
    int dataRead;
    while ((dataRead = fromStream.Read(bytes, 0, bytes.Length)) > 0)
        toStream.Write(bytes, 0, dataRead);
}

his blog 上的扩展方法归功于 Gunnar Peipman .

关于c# - 如何获取System.Net.Mail.Attachment的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19360503/

相关文章:

c# - 是否可以将一个 Web 用户控件注入(inject)另一个 Web 用户控件?

c# - 如何让 EF6 生成高效的 in(...) 查询

iphone - pdf 作为 iOS 设备中的电子邮件附件

ruby-on-rails - Rails 3、Action Mailer、附件、form_for、电子邮件

c# - GAE Flexible 不使用 CORS 返回正确的响应 header

c# - 避免 C# 虚拟调用的开销

C# - 如何将特定记录从数据库显示到 ASP.NET MVC 中的 View

Python Sendgrid 发送带有 PDF 附件的电子邮件

c# - 将文件附加到电子邮件而不创建文件

Java 邮件附加文件在下载后显示损坏