我有一个 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/