C# 如何获取System.Net.Mail.Attachment的内容
我有一个System.Net.Mail.Attachment对象,其中包含一些.csv数据。我需要将附件的内容保存在一个文件中。我试过这个:C# 如何获取System.Net.Mail.Attachment的内容,c#,email-attachments,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");
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只是一个抽象流(在运行时它是一个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);
}
感谢Gunnar Peipman在上的扩展方法。假设您的流不是太大,您可以将其全部写入文件,如下所示:
StreamWriter writer = new StreamWriter(@"C:\Blah\Look.csv");
StreamReader reader = new StreamReader(attachment.ContentStream);
writer.WriteLine(reader.ReadToEnd());
writer.Close();
如果它更大,您可能希望将读取数据分块到一个循环中,以避免破坏RAM(并冒内存不足异常的风险)。使用file writer将该流写入文件?您不能在随机流上调用
ToString
,通常只打印类型名称。您需要使用CopyTo
将流复制到另一个流。如果它不是太大,您可能只需调用ContentStream.ReadToEnd()
@KevinDiTraglia,这将不起作用,因为ContentStream
只是一个系统.IO.stream
,而不是文本阅读器。即使使用强制转换,也可能失败。如果不使用ToString()我也会得到同样的结果。@DavidShochet也许,也许不是。它们都完成了相同的任务,这将为非常大的文件附件使用更少的内存,因为它是缓冲的。